Retrieving and assigning data values within an Angular JS service

Here is the service I created to fetch user details:

angular.module('app')
.factory('userDetailService', function($http) {
    var userData = {};

    function getUserDetails(userId) {
        if (userId) {
            return $http.get("/users/" + userId).success(function(data) {
                angular.copy(data[0], userData);
            });
        }
    }
    return {
        userData: userData,
        getUserDetails: getUserDetails
    }
})

In Controller 1, I am using this service successfully to retrieve relevant data:

$scope.getUserId = function(userId) {
        if (userId) {
            $scope.userData = userDetailService.userData;
            userDetailService.getUserDetails(userId).success(function() {
                console.log($scope.userData); //Prints valid user data
            });
        }
 };

However, when I try to access userData in Controller 2:

$scope.userData = userDetailService.userData;
console.log($scope.userData); //Prints null

The value of $scope.userData is null. Shouldn't I be able to access the data shared by the service between controllers? Why does it work in one controller but not in the other?

Interestingly, a modal dialog template in Controller 2 can access data with {{userData.first_name}} and {{userData.last_name}}. If this works, why is $scope.userData null? What am I missing?

Edit:

Template 1:

<div id="myModal" ng-controller="Controller 1">
<modal-configure-user></modal-configure-user>
    <a data-toggle="modal" data-target="#configureUserModal" href="#" ng-click="getUserId(user.id)" data-id="user.id">{{user.first_name + ' ' +user.last_name}}</a>
</div>

Template 2:

<div ng-controller="Controller 2"  id="configureUserModal">
</div>

Both are modal dialog windows.

Answer №1

Your current method may not always be reliable as there is no guarantee that the data has loaded before accessing it in the second controller. It is recommended to use the getUserDetails method, which returns a promise, instead of directly assigning user data to a variable. By caching the loaded data, you can avoid making duplicate requests.

angular.module('app')
.factory('userDetailService', function($q, $http) {

    var userData;

    function getUserDetails(userId) {
        if (userId) {
            return userData ? $q.when(userData) : $http.get("/users/" + userId).success(function(data) {
                userData = data;
                return userData;
            });
        }
    }

    return {
        getUserDetails: getUserDetails
    }
});

By wrapping userData with $q.when, you create a promise object that resolves immediately. This ensures consistency in the service API by always working with promises.

The usage in both controllers would then be as follows:

userDetailService.getUserDetails(userId).then(function(data) {
    $scope.userData = 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

Issue with Angular Reactive form: Checkbox checked property not binding correctly when the page initially loads

Looking to achieve Two-way data binding of Checkbox in Angular Reactive forms. After checking the checkbox, I am updating the 'isdateChkd' variable and storing it in the state. Despite the variable being set to TRUE, the checkbox does not get aut ...

VueJS does not update values instantly as they change

I have implemented a JS class with the following code: class Field { public Value = null; public Items = []; public UniqueKey = null; public getItems() { let items = [...this.Items]; items = items.filter((item) => { ...

Exploring a different method for implementing animations during UI-router state transitions

My product owner presented me with a seemingly impossible challenge to create animations between states. I utilized ngAnimate and thought I had a brilliant solution - only to be told it wasn't what they wanted. "This isn't what I had in mind," h ...

Retrieving data from radio buttons using React Hook Form

As I delve into learning React and Next.js, working with form submissions has been a breeze thanks to react-hook-form. However, I've hit a roadblock when it comes to handling radio buttons in my application. Specifically, there's a step where use ...

Tips for accessing a value in a multidimensional json array without the key in JavaScript/jQuery?

I'm working with a JSON file that contains a multidimensional array. The array consists of city data at the first level and temperature data at the second level. I'm facing difficulties in dynamically extracting values from the second level. I a ...

Node and Web scraping Promise: a powerful combination

I've been using Cheerio and Node for web scraping, and I thought implementing promises could simplify handling asynchronous code. However, my attempt to chain promises hasn't been successful. Below is the code I'm working with, in hopes that ...

Can anyone suggest a method for adding comments and improving the organization of a bower.json file?

Managing a large project with numerous bower dependencies can be challenging. It's often unclear whether these dependencies are still being used or if the specified versions are necessary for a reason. It would be ideal to have the ability to add comm ...

cross-domain policy file

Currently, I am attempting to make a web service call from JavaScript using AJAX: $.ajax({ type: "GET", url: "http://[REMOTE-SERVER-IP]:8080/api/service", contentType: "application/jsonp", crossDomain: true, success: successFunc, ...

Issues encountered when passing JavaScript object to PHP

I'm attempting to transmit my JavaScript object to PHP using JSON.stringify() JavaScript: $('#save').on('click touch', function(){ obj = { "1" : { "1" : "hey", "2" : "hay" }, ...

Establishing the bottom limit for the vertical axis on a column chart with the Visualization Google API

I am currently working on implementing the Google Chart API alongside AngularJS. I attempted to adjust the min property of the vertical axis for my column chart to 0 using the following code: var dataMois = CaDuMois.query(function(){ $scope.comparat ...

Patiently waiting for the component variable to be assigned through subscription

I am facing an issue with two calls in my component. The second call depends on the result from the first call. In the first call, I set the value for my component variable "locked". The second call should only be executed when the result is true, meaning ...

Identifying the specific promise that failed within a chain of .then statements

I am currently working on setting up a chain of promises with an error catch at the end within my node and express application. One issue I have encountered is that if any of the 'then' functions encounter an error, it can be difficult to trace b ...

What is the process for assigning an item from the result list to the parent Div tag of the current object?

I've been working on a function to insert the number of Facebook Likes into a Div tag. The script I have so far can extract the URL from a Div tag inside another Div named 'entry'. Then, using the .getJSON() method, it fetches the Facebook l ...

c# JavaScriptConverter - understanding the deserialization of custom properties

I'm facing an issue where I have a JSON serialized class that I am trying to deserialize into an object. For example: public class ContentItemViewModel { public string CssClass { get; set; } public MyCustomClass PropertyB { get; set; } } Th ...

Mastering the art of Puppeteer with Javascript

I am currently learning how to make web requests using JavaScript with puppeteer. After some trial and error, I was able to extract the value of a tag from a random website. However, I am struggling to figure out how to retrieve 10 consecutive values of ...

What is the process for sending a request to Electron from my backend using NAPI?

I'm currently working on a project using Electron, and I have a NAPI file that contains my backend code. In my user interface, when a specific button is clicked, it triggers a function that calls the function from NAPI. Electron acts as the bridge bet ...

Tips for changing the size and color of SVG images in a NextJS application

Looking to customize the color and size of an svg image named "headset.svg". Prior to this, I used next/image: <Image src={'/headset.svg'} alt='logo' width={30} height={30} className='object-contain' /> The s ...

Loading necessary CSS when needed in React JS

I am currently in the process of converting a bootstrap template to react framework. My question is, is there a way for me to load stylesheets on demand? For instance, if I have 2 components and I import the same stylesheet separately in both components, ...

Having difficulty displaying JSON data in a react component

I am currently working on parsing JSON data retrieved from an Ajax call in order to display it in a table using the React DataTable component. However, I have encountered a problem while trying to store the data in a state variable using the setState metho ...

I encounter a black screen issue while attempting to rotate a three.js cube

How can I rotate a cube around all three axes (x, y, z) using the code snippet provided below? ` <html> <head> <title>CM20219 – Coursework 2 – WebGL</title> <meta charset="utf-8"> < ...