"Implementing an AngularJS factory that returns a State object instead of typical JSON data fetched from

I have created two factories and I am calling the first one from the second one in my controller. However, instead of receiving JSON data, I am getting data as $$State. I am new to AngularJS and have tried multiple solutions but have not been able to resolve this issue. Can someone please assist me with this problem?

 app.factory('userDetails', ['APIService', '$q', function (APIService, $q) {
    getDetails: function () {
        var deferred = $q.defer();
        var getFunc = function () {
            APIService.doGetCall('Masters/employee/username/tarun')
                .then(
                function (data)
                { 
                    deferred.resolve(data);
                },
                function (data, status, headers, config)
                { 
                    deferred.reject('There was an error creating object'); })
                    return deferred.promise;
                 }
        var a = getFunc();
        return a;

    }
}

 vm.user = userDetails.getDetails();
console.log("user",vm.user);

The response is shown in the following snippet:

Response

Answer №1

To obtain a response, it is advisable to utilize the .then function. Creating an additional promise is considered an anti-pattern, as you can directly use the promise returned by the doGetCall method.

app.factory('userDetails', ['APIService', '$q', function(APIService, $q) {
  getDetails: function() {
    var getFunc = function() {
      return APIService.doGetCall('Masters/employee/username/tarun');
    }
    var a = getFunc();
    return a;
  }
}]);

vm.user = userDetails.getDetails().then(function(response){
    console.log(response.data);
    vm.user = response.data;
    console.log("user", vm.user);
}, function(error){
    console.log(error)
}).catch(exceptionHandler);

Answer №2

When calling userDetails.getDetails(), keep in mind that it returns a promise. Therefore, you must utilize the .then(onsuccess, onRejected) method.

userDetails.getDetails().then(function(data){
   vm.user = data;
   console.log("user",vm.user);
});

Answer №3

Make sure to move the

return deferred.promise;

line outside of the APIService.doGetCall function and put it at the end instead.

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

The script remains static and does not alter the "href" or "div" content based on the current URL

I am having an issue with my NavMenu on my website. It is a table with images that link to product pages, and I want to change the links and names based on the language of the site. However, the script I wrote for this is not working properly. I have tried ...

I'm unsure of my recollection on how to utilize the /* syntax in JavaScript

Hey there, I'm facing a little issue. Can someone remind me how to correctly use the /* in JavaScript when dealing with URLs? For instance: if(URL == "www.thing.com/"){} I can't quite remember where to insert the /* so that it applies not just ...

"Exploring the power of Node.js by utilizing ObjectArray and implementing

Can I compare two arrays of objects in JavaScript? My goal is to find the common objects between these two arrays: First object array: [ { id_0: 356, name_0: 'xxxxx', id_1: 33, name_1: 'yyyyyy', id_ ...

Tips for preventing the colors of all buttons from changing when only one is clicked in JavaScript

const tasks = `[{ "taskName": "Task 1", "image": "./images/task1.jpg", "description": "Task 1 description", "importance": 0 }, { "taskName": "Task 2", "image": "./images/task2.jpg", "description": "Task 2 description", ...

Issue with Jquery Slider Showing Empty Slide

Currently addressing issues with the slider on my site, which utilizes SlidesJS at . There seems to be a problem where it shows a blank slide inexplicably. After investigating, I noticed that a list element is being added to the pagination class, but I can ...

Using Angular 8, remember to not only create a model but also to properly set it

hello Here is a sample of the model I am working with: export interface SiteSetting { postSetting: PostSetting; } export interface PostSetting { showDataRecordAfterSomeDay: number; } I am trying to populate this model in a component and set it ...

Tips for retaining user input in an input box using HTML and AngularJS

Is there a way to retain a user's input in an input box? This is the current code snippet: <input type="text" ng-model="userText" placeholder="Enter text here"> However, I am looking for a solution that will allow the entered text to persist ...

Is the navigation dropdown toggle triggered by both mouseout and when hovering off of it?

I'm looking for some assistance in modifying the code so that the dropdown menu not only hides on click, but also hides on mouseout and/or when another top-level menu button is hovered over. View jsfiddle example $(document).ready(function () { ...

Dynamically loading a JSON file in JavaScript

Can you please review this code snippet? var scripts = {}; require = function(src){ var id = Math.round(+new Date()/1000); $.ajax({ url: src + '.json', type: 'GET', dataType: "json", cache: ...

Handling invalid unicode characters in JSON with Golang Decoding/Unmarshaling

I've encountered some inconsistency in the formatting of JSON files while fetching them in Go. For example, the data could look like this: {"email": "\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa98969b92d498969 ...

Are web components capable of managing changes in CSS (maybe through cssChangedCallback)?

Is there a way to control the application of CSS to a web component similar to using attributes through attributeChangedCallback. I am currently developing a couple of web components that could benefit from being styled with CSS classes. However, I requir ...

Triggering server-side code (node.js) by clicking a button in an HTML page created with Jade

I am currently working on developing a web application and have encountered an issue where I need to execute some server-side code when a button is clicked (using the onClick event handler rather than the Submit button). My tech stack includes Node.js, Exp ...

Adjust the value of a select box to the chosen option using JQuery

Could someone please assist me with this code? I am trying to adapt it for use on my mobile device with jQuery Mobile. var obj = jQuery.parseJSON(finalresult); //alert(obj); var dept = '2'; $(document).ready(function () { //$("#opsContactId ...

How can PHP Curl be used to retrieve a corresponding value from a JSON data?

On my webpage, I have some jSON data that I need to gather into arrays using cURL in PHP code, not through the command line. The code snippet below shows how I currently achieve this: $token = 'my_token_here'; $headers = ['Authorization: B ...

Maintain functionality of React components even when they are not actively displayed

I have a unique page React app with different components. The App.js file controls which component to display based on server information. One specific component, the Stopwatch, is only rendered on two of the pages. Here's a snippet of code from my Ap ...

Reactjs is having issues with Datatable functions

I am making use of the Datatable Library for creating tables easily. After fetching data with the Fetch API and rendering it to the table, everything seems to work smoothly. However, I am facing issues with DataTable Functions such as sorting, searching, ...

Use nodejs with multer alongside angularjs to enable smooth file uploads without any redirection

I'm currently working on a file uploading feature using Nodejs, Multer, and AngularJS. I have a straightforward HTML file: <form action="/multer" method="post" enctype="multipart/form-data"> <input type="file" id="photo" name="photo"/&g ...

Establish the state as the result of a function

I need to update the state of timeToCountdown with the value stored in allTimeInSeconds. Next, I intend to pass this data as a prop to a component. class Timer extends Component { constructor(props){ super(props); this.state = { ...

What causes the variable to be invisible in the imported file?

Within the main.js file, there is a specific code snippet: var test_mysql = require('./test_mysql.js') ... //additional code before(function(){ test_mysql.preparingDB(test_mysql.SQL_query.clear_data); // or test_mysql.preparingDB(SQL ...

Guide to sending back a promise using JQuery

Here is the Durendal code I am working with: var variable = ko.observable(""); function activate(){ return myModel.doSomething(variable); } The doSomething function looks like this: function doSomething(variable){ if(someCondition) return ...