The $http success function is returning an undefined variable for a custom AngularJS service

In my recent development project, I created an angular service with the purpose of loading customer details through http requests and storing them for future use using a singleton pattern.

However, I encountered an issue where the variable intended to hold the fetched data becomes undefined upon successful completion of the http call, resulting in an error being thrown.

Below is the snippet of code responsible for this functionality:

NBApp.service("serverDataService", ['$http', '$q', function ($http, $q) {
    var currentMemberDetails = [];

    this.currentMember = function (){
        if (this.currentMemberDetails.length>0)
            return this.currentMemberDetails[0];
        return null;
    };

    this.getMemberDetails = function (cardId) {
        //TBD - call members details web service
        var deferred = $q.defer();
        $http({
            method: 'GET',
            url: 'resources/customer.json'
        }).then
        (
            function success(response) {
                this.currentMemberDetails.push(response.data);
                deferred.resolve(data);
            },
            function failure(response) {
                deferred.reject(response);
            }
        );
        return deferred.promise;
    };
}]);

The Chrome dev console confirms that currentMemberDetails remains undefined after the http call is made.

Answer №1

Swap out

this.currentMemberDetails.push(response.data);

Try

currentMemberDetails.push(response.data);

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

Exploring the Power of Webpack and Web Workers within Ionic 2

In our upcoming Ionic 2 project, we are considering the implementation of web workers. However, due to the usage of ionic-app-scripts (version 1.0.0) with webpack in Ionic 2 (https://github.com/ionic-team/ionic-app-scripts), we face the challenge of having ...

The solution for fixing contenteditable is as follows:

I am currently working on a script to clean up pasted text within a contenteditable div. While the script is functioning well for most part, I have noticed that in Firefox, line breaks get removed when the text is copied within or between the divs. Does ...

Javascript - Issue: Route.post() is in need of a callback function, however it received an [object Promise] instead

I'm encountering an issue with one of my express routes. The error message I am receiving is as follows: Error: Route.post() requires a callback function but got a [object Promise] This error seems to be related to the last line in controllerFunction ...

React and Material UI: Ensuring Proper Whitespace Handling in Strings

Exploring the use of Typography component from Material UI (https://material-ui.com/api/typography/) The main objective is to maintain the new lines and spaces in a saved string. For instance, if the string contains leading spaces and new lines, it shoul ...

Tips for integrating an image with form.serialize() function?

When attempting to add an image in the form.serialize, it appears to not be functioning properly. The form in question is provided below: var frm = $('#id_article_form'); var formData = $('#id_article_form').serializeArray(); formDat ...

Creating a dynamic parallel route in Next.js by utilizing a static route trigger

In my work with Next.js, I have established the following routes: /@modal/(.)snippets/[id]/page.tsx (serving as a modal) /snippets/[id]/page.tsx (for individual snippet pages) /snippets/new/page.tsx (to create new snippets) An issue arises when I try to ...

Once deployed, Google Cloud Function experiences delayed execution

I have implemented a Cloud Function that executes the following steps: retrieving data from an API formatting the retrieved data saving the data in Firestore Here is the code snippet for my implementation: exports.syncItems = functions.https.onRequest((r ...

Using Angular 2 to create an Observable type that mediates two separate http.get calls

In my ng2 service, I have a method that contains two http.get calls. Here is an example of the function: getInfo(userId: number): any { this.http .get(apiUrl, options) .map(response => response.json()) .subscribe(example => ...

Updating default values in reactive() functions in Vue 3: A step-by-step guide

Currently, I am in the process of developing an application using Nuxt 3 and implementing the Composition API for handling async data. The specific scenario I am facing is this: I have a page that displays articles fetched from the database using useLazyFe ...

Automatically navigate to a specific element as the user scrolls down the page

I am attempting to achieve a similar effect as seen on the App Builder Website. When the user reaches the header with the background image/video and scrolls down, the website smoothly transitions to the next div/section. If the user scrolls back up and ret ...

`How can I use JavaScript filter to refine element searches?`

Struggling to get this filter function to work correctly. I configured it to filter and display only the desired items based on the card's classname (landing-pages-list). Unfortunately, the function is not functioning as expected. How can I make it w ...

Exploring items in React by utilizing a separate object

Hey there, I've got something that's been working really well for me: const handleFavour = () => { const { developers } = state; const results = developers.filter(list => list.uid.includes("authid") ); setSearchResults(results) ...

What is the method for notifying the latitude within this Google Maps javascript code?

There's a specific line that triggers an alert showing "undefined". However, when I just alert results[0].geometry.location, it displays (41.321, 41.556). My goal is to alert this value and then convert it (as an integer) to my id_lat and id_longs... ...

Is it time to refresh the sibling element when it's selected, or is there

I have recently started working with react and TypeScript, and I am facing some challenges. My current task involves modifying the functionality to display subscriptions and transactions on separate pages instead of together on the same page. I want to sh ...

Clicking an element causes popovers to vanish

I have encountered an issue with my popovers. I am trying to trigger them through a function that is called by an onclick event. Strangely, they disappear within a second. They work fine when checked individually, but once the user presses the "submit" but ...

Retrieve class property in Angular by its name

How can I retrieve an array from a class like the one below without using a switch statement, dictionary, or other collection to look up the name passed into the method? export class ProcessOptions { Arm = [{ name: 'Expedited Review ("ER") ...

Ways to implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

Modifying the URL of an AJAX call prior to sending

I am looking to dynamically insert the data entered in a text box labeled 'postcode' into the URL parameters 'VALUE1' and 'VALUE2'. Unfortunately, I lack examples to provide as I am unsure of where to begin. <input type="t ...

Is Your Website Sluggish because of an Excessive Amount of JavaScript on Page

After finally resolving some of the Javascript issues I was facing, I have streamlined my code to utilize just one library now, which is a huge improvement from how chaotic it was before. However, I have noticed a slight delay in the page load time, and I ...

Pressing the button will add text into the input field

Below is a jsfiddle link showcasing the current issue I am trying to address: http://jsfiddle.net/YD6PL/61/ Here is the HTML code snippet: <input type="text> <input type="text> <input type="text> <div> <button class="buttons"& ...