Fulfill the promise in AngularJS and assign it to a different factory

Presenting my factory below:

.factory('UserData', ['User', '$q', function(User, $q) {
    var deferred = $q.defer();

    return {
        user: null,
        get: function() {
            var _this = this;
            _this.user = User.get();
            deferred.resolve(User.get());
            return deferred.promise();
        }

    };

}]);

In the User factory, there is some relevant data available which can be retrieved using User.get(). My goal is to retrieve this data and assign it to user: null in my UserData factory.

Answer №1

Solution:

.service('UserData', ['User', '$q', function(User, $q) {
   var _service = {};

   _service.user = null;

   /* returns a promise that resolves to user value */
   _service.get = function() {
     // return cached user as a resolved promise
     if (_service.user) return $q.resolve(_service.user);

     return User.get().then(function(user) { // chain User.get() promise
       return _service.user = user; // cache user value in _service.user
     });
   };

   return _service;
}]);

It seems like you might prefer using a cached version (just return value if service.user is already populated). You can simply remove the caching part if this isn't necessary.

Additionally, consider whether or not you want to expose the user variable as part of the service. If not, you may want to declare it as a variable instead and modify references to _service.user to conceal internal implementation details.

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

Iterate over an array of objects to showcase the property values within an HTML tag using JavaScript

I am a beginner in JavaScript and I am currently working on an exercise. My goal is to iterate through an array of objects within another object, map the index values from one object to the id values in another object, and based on that, perform a certain ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

Using AngularJS, you can easily merge one array of data into another array

In my coding environment, I am working with two arrays. The first array is called `$scope.workingSchedules` and it contains data related to working hours for different days of the week. $scope.workingSchedules=[ { ...

Tips for choosing specific characters from a string using JavaScript

When dealing with URL strings like "example.com/Apps/Visitor/visitscanner" , "example.com/Apps/Seatings/visitscanner I am interested in extracting the directory name following the "http://example.com/Apps/" For the above examples, if the URL string is " ...

When the mouse leaves, the gauge chart component's size will expand

I have encountered a problem while using the react-gauge-chart library in my react project. Within the project, I have integrated a popover component using material-ui and incorporated the gauge chart component from the library within the popover modal. T ...

Tips for locating all events linked to a specific text box using JQUERY

I'm currently encountering a major issue with textboxes on a page that I've been tasked to update. Whenever I attempt to input text into the textboxes, the span element next to them disappears. My application is built using ASP.NET and relies on ...

Leveraging Object.assign for updating fields in Firebase documents

Currently, I am working on a website that allows users to create new projects by filling out a form with all the necessary project information. Within this form, there is a file input field where users can upload images and documents. I have successfully i ...

Mapping arguments as function values

Hello there, I have an array of objects that I am attempting to map through. const monthObject = { "March 2022": [ { "date": "2022-03-16", "amount": "-50", &q ...

What is the proper way to update data in reactjs?

I previously had code that successfully updated interval data in the browser and locale without any issues. class Main extends Component { constructor(props) { super(props); this.state = {data: []} } componentWillMount() { fetch('fi ...

Insert a blank row at the top of the grid in Wijmo for Angular 2

I am attempting to insert a new empty row at the start of the grid when an external button is clicked. The grid is displaying correctly. <wj-flex-grid #flex [itemsSource]="data" [isReadOnly]="true" [headersVisibility]="'Column' ...

React-querybuilder experiencing issues with validator functionality

While utilizing the react-querybuilder, I have encountered an issue with field validation not functioning correctly. Upon reviewing this StackBlitz, it appears that when clicking on Rule and checking all fields, there are no errors present. export const fi ...

What is the process of utilizing jQuery to hover over a relevant cell?

I'm interested in learning how to implement jQuery to highlight related tables. Initially, I explored this JS fiddle and discovered a method for highlighting both vertically and horizontally. I conducted several searches to find a similar approach, ...

Detecting the scroll events of elements with the overflow:hidden property

Looking to synchronize scrolling between two different panels or divs? In one element, there's an overflow: auto while the other has overflow: hidden (trying to mimic a grid with frozen columns). I've managed to sync the scroll when it occurs w ...

Update the state when a button is clicked and send a request using Axios

Currently in my front end (using react): import '../styles/TourPage.css'; import React, { Component } from 'react'; import axios from 'axios' class TourPage extends Component { constructor(props) { super(p ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Discovering, storing, and displaying JSON data in JavaScript

I am currently working on a PHP file called rows2.php that displays results from a database by showing the new id of the field in this format: {'new_id':'92'} My goal is to use JavaScript to load this data and add the new_id surrounded ...

Having trouble utilizing Reactjs Pagination to navigate through the data

I'm currently working on implementing pagination for a list of 50 records, but I'm encountering an issue. Even though I have the code below, it only displays 10 records and I'm unaware of how to show the next set of 10 records until all 50 a ...

Comparison of Node.js and Express.js APIs for handling responses

Both Node.js and Express.js have their own unique response APIs. Interestingly, there are some similarities between the two, such as: Node.js: response.write(chunk[, encoding][, callback]) Express.js: res.attachment([filename]) res.download(path [, ...

Tips for implementing a jQuery mouseleave function for multiple div elements sharing the same id

I am facing an issue with my website where multiple divs share the same id. I need to implement a mouseleave function for all of these divs that have this specific id. Within my $(document).ready function, I currently have the following code... $('#m ...

Show all column data when a row or checkbox is selected in a Material-UI datatable

I am currently working with a MUI datatable where the properties are set as below: data={serialsList || []} columns={columns} options={{ ...muiDataTableCommonOptions(), download: false, expa ...