"Converting a basic function into a promise for an AngularJS tutorial: How to handle the error message '

To help my colleagues understand AngularJS, I am creating a dummy exercise. In this example, I want to call a service that provides an Object Array to be passed into a Controller and assigned to a $scope variable (using information about the Beatles). Instead of building a REST service, I plan to return a static / hard coded Object Array from my service. However, the service does not return a promise which causes an error when trying to use the .then() method.

TypeError: AlbumsService.fetchBeatlesAlbums(...).then is not a function

In typical data retrieval using $http, we would utilize .then(), so I want to find a way to simulate this behavior in my exercise. Below are the controllers and service with comments indicating where the error occurs:

angular.module('beatlesApp', []) // Defining the app name and dependencies
    .controller('MainCtrl', ['$scope', function($scope) {
        // Setting $scope variables
    }])

    .controller('ChildCtrl', ['$scope', 'AlbumsService', function($scope, AlbumsService) {
        // Setting $scope variables

        // ERROR OCCURS HERE... AlbumsService.fetchBeatlesAlbums(...).then is not a function    
        AlbumsService.fetchBeatlesAlbums().then(function(resp) {
            $scope.albums = resp;
        });
    }])

.service('AlbumsService', function() {
    // Service providing data - data is hardcoded for this example

    this.fetchBeatlesAlbums = function() {
        return [{
            name: 'Please Please Me',
            released: '1963',
            pic: 'please.jpg'
        }, {
            name: 'With the Beatles',
            released: '1963',
            pic: 'with.jpg'
        }, {
            name: 'A Hard Day\' s Night',
            released: '1964',
            pic: 'hard.jpg'
        }, {
            name: 'Beatles For Sale',
            released: '1964',
            pic: 'bfs.jpg'
        }, {
            name: 'Help!',
            released: '1965',
            pic: 'help.jpg'
        }, {
            name: 'Rubber Soul',
            released: '1965',
            pic: 'rubber.jpg'
        }, {
            name: 'Revolver',
            released: '1966',
            pic: 'revolver.jpg'
        }, {
            name: 'Sgt Pepper\'s Lonely Hearts Club Band',
            released: '1967',
            pic: 'splhb.jpg'
        }];
    };
});

Answer №1

Here's a working solution:

  .service('AlbumsService', function($q) {

    this.fetchBeatlesAlbums = function() {
        var defer = $q.defer();
        var arr = [{
            name: 'Please Please Me',
            released: '1963',
            pic: 'please.jpg'
        }, {
            name: 'With the Beatles',
            released: '1963',
            pic: 'with.jpg'
        }, {
            name: 'A Hard Day\' s Night',
            released: '1964',
            pic: 'hard.jpg'
        }, {
            name: 'Beatles For Sale',
            released: '1964',
            pic: 'bfs.jpg'
        }, {
            name: 'Help!',
            released: '1965',
            pic: 'help.jpg'
        }, {
            name: 'Rubber Soul',
            released: '1965',
            pic: 'rubber.jpg'
        }, {
            name: 'Revolver',
            released: '1966',
            pic: 'revolver.jpg'
        }, {
            name: 'Sgt Pepper\'s Lonely Hearts Club Band',
            released: '1967',
            pic: 'splhb.jpg'
        }];
        defer.resolve(arr)
        return defer.promise;
    };
});

Answer №2

To mimic the behavior of $http, you can utilize the $q service along with the $timeout service to create a promise.

Here is an example implementation:

.service('AlbumsService', function($q, $timeout) {

    this.fetchBeatlesAlbums = function() {

        var deferred = $q.defer();

        $timeout(function() {
            deferred.resolve([{
                name: 'Please Please Me',
                released: '1963',
                pic: 'please.jpg'
            }, {
                name: 'With the Beatles',
                released: '1963',
                pic: 'with.jpg'
            }, {
                name: 'A Hard Day\' s Night',
                released: '1964',
                pic: 'hard.jpg'
            }, {
                name: 'Beatles For Sale',
                released: '1964',
                pic: 'bfs.jpg'
            }, {
                name: 'Help!',
                released: '1965',
                pic: 'help.jpg'
            }, {
                name: 'Rubber Soul',
                released: '1965',
                pic: 'rubber.jpg'
            }, {
                name: 'Revolver',
                released: '1966',
                pic: 'revolver.jpg'
            }, {
                name: 'Sgt Pepper\'s Lonely Hearts Club Band',
                released: '1967',
                pic: 'splhb.jpg'
            }]);
        }, 1000); //Delays return by 1 second.

        return deferred.promise;
    };
});

Combining $timeout with $q allows for creating a genuine delay in data retrieval instead of an instant response provided by $q alone.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering whether an ID exists within a variable containing HTML code

I am currently attempting to determine if the ID is included in a variable containing HTML content. The ID name is being added to a DIV element through dynamic variables. strHTML = "<div id='"+var1+var2+"'>" Now, I want to verify if a sp ...

Display and conceal div with Jquery as you scroll to specific points on a mobile device

I'm looking to create a dynamic div that appears and disappears based on the user's scroll position. Here is what I have so far: $(document).scroll(function() { var y = $(this).scrollTop(); if (y > 200) { $('.float-contai ...

What is the best way to extract the event time when a user clicks on an event in fullcalendar?

Is there a way to extract only the time from an eventclick event in fullcalendar? Currently, I am receiving details about the event including date and time. How can I specifically retrieve just the time (e.g. 6:00:00 am)? You can find the code snippet tha ...

Automatically install the development version of NW.js when running 'npm i'

Is it possible to automate the installation of the developer version of NWJS from package.json, similar to when I run npm install? For example, if I type npm i nw --nwjs_build_type=sdk I attempted to set an environment variable in my package.json like th ...

Replacing a string in a textarea using Jquery

Trying to dynamically replace a string value in a textarea while typing into a textbox using jQuery. Utilizing the keypress event for this functionality. Any ideas on what could be causing issues with this example? <input type="text" id="textbox" /> ...

How can you utilize jQuery to export multiple-page HTML content into a PDF document?

I'm having trouble exporting HTML to PDF using jQuery, especially when the HTML content spans multiple pages in the PDF file. Below is my current code snippet: $("body").on("click", "#downloadPDF", function () { html2canvas($('#dow ...

Ways to ensure the axios call is completed before proceeding with the codeexecution

I need to use axios to send a request and retrieve some data that I want to pass as a prop to a React Component. Here's my render function: render() { boards = this.fetchBoardList(); return ( <div className="app-wrapper"> ...

Facing challenges in both client-side and server-side components

import axios from 'axios'; import Image from 'next/image'; export const fetchMetadata = async({params}) => { try { const result = await axios(api url); return { title: title, description: Description, } / } catch (error) { con ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...

Circular dependency in AngularJS objects occurs when two or more modules depend

In my scenario, I have two entities: a House and a Tenant. Both of these are created and described using factory methods. The application is designed in such a way that each Tenant can be associated with multiple houses, and each House can have more than o ...

Removing a specific item from a Kendo UI dropdown list

Recently, I encountered a predicament with a dropdownlist populated from a datasource. Following a certain event, my goal is to eliminate a single item from the dropdownlist identified by id = 22. Although I recognize this may not be the best practice du ...

The placeholder feature seems to be malfunctioning when it comes to entering phone numbers in a react

I am working on a MUI phone number form field. I want the placeholder to show up initially, but disappear when the user starts typing. How can I achieve this functionality in my code? import React from "react"; import MuiPhoneNumber from " ...

Avoid constantly destroying the Bootstrap Popover

I am facing a challenge with retrieving data from two checkbox inputs inside a popover. The issue arises because the popover appears in the DOM when I click a button, but is removed when I click it again. It seems that the problem lies in the fact that Jav ...

Using $.getJSON is not functioning properly, but including the JSON object directly within the script is effective

I'm currently working on dynamically creating a simple select element where an object's property serves as the option, based on specific constraints. Everything is functioning properly when my JSON data is part of the script. FIDDLE The follow ...

Import data from JSON using JavaScript

I have a collection of txt files that contain custom content. The file names are stored in a JSON array. { txtFiles: ['./file1.txt', './file2.txt', './file3.txt'] } I am looking to use the require function in JavaScript t ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

Whenever I attempt to import the "Highway" package, I encounter an error stating "Unexpected identifier."

After installing Highway through the terminal, I encountered an issue when running the script below: import Highway from '@dogstudio/highway'; import Fade from './transition'; const H = new Highway.core({ transition: { default: ...

Tips for including a header with Apollo Client in a React Native app

In my React Native application, here's how I set up the Apollo client with an upload link: My goal is to include a header with a token value that will be sent with every request. However, I've had trouble finding an example specifically for Reac ...

Angular Datepicker MinDate function prevents selection of dates "behind" by one

I've encountered an issue with the Angular Bootstrap Datepicker where I'm setting the min-date attribute as follows: <input type="text" class="" uib-datepicker-popup="MM/dd/yyyy" show-button-bar="false" ng-model="vm.date" ng-change= ...

Error in D3: stream_layers function is not defined

Utilizing nvd3.js to construct a basic stacked bar chart as detailed here I inserted the code provided in the link into an Angular directive like this: app.directive('stackBar', function() { return { restrict: 'A', ...