Tips on exposing promise data object in the controller and transferring data from the promise to a new function

After creating an angular controller and service to extract data from a JSON file, everything seemed to be working smoothly. However, I encountered an issue when attempting to assign this data to a new object.

My goal is to implement a new function within my promise that accepts the data as an object, allowing me to utilize it in various parts of the application. Here is the code for the controller:

class WPEntryController {
    static $inject = ["$location", "WPEntryService"];
    constructor($location, WPEntryService, $http) {
        console.log("IN WPEntryController");
        this.$location = $location;
        this.WPEntryService = WPEntryService;
        this.loadWPEntryPagewithData();

    }
    loadWPEntryPagewithData(){
        this.WPEntryService.loadWPEntryData().then(function(promise){
           this.DataObject = promise;
            this.storeObject();
        });
    }
    storeObject() {
        console.log(this.DataObject);
    }
}
angular.module("app").controller("WPEntryController", WPEntryController);

Here is the service code:

class WPEntryService {
  static $inject = ["$http"];
  constructor($http) {
    this.$http = $http;
  }
    loadWPEntryData() {
        // read json file or provide URL for data
        var promise = this.$http.get('...')
            .then(function (dataObject) {
                return dataObject.data;
            })
            .catch(function (response) {
                return response;
            });
        return promise;
    }
}

angular.module('app').service('WPEntryService',WPEntryService);

Answer №1

Ensure you have the correct this context within your then callback by using an arrow function like so:

loadWPEntryPagewithData(){
    this.WPEntryService.loadWPEntryData().then(dataObject => {
//                                             ^^^^^^^^^^^^^^
        this.DataObject = dataObject;
        this.saveToStorage();
    });
}

To improve reliability, consider storing the promise itself in that instance slot instead:

loadWPEntryPagewithData(){
    this.DataPromise = this.WPEntryService.loadWPEntryData();
    this.saveToStorage();
}
saveToStorage() {
    this.DataPromise.then(DataObject => console.log(DataObject));
}

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

Nested ng-repeat containing single select checkboxes

For more information, please refer to the demo plunkers provided below: Demo Plunker Example1 The code snippet for Example1 is as follows: <tr ng-repeat="class in Classes"> <td>{{class.name}}</td> <td&g ...

Adding substantial sections of HTML without any adjustments

While I am working on DOM manipulation, I have encountered the need to insert large blocks of HTML. I am looking for a more efficient way to do this rather than relying on concatenation or creating a messy code structure. Consider the simple code snippet b ...

Once more, objects cannot be used as a child element in React

I understand that there are similar questions about this topic, but I am struggling to approach it in a different way. I really need an array of objects to be inside a map. I have created an array to map it, but I need to find different information to disp ...

Show only half of the Google Charts

I have a code snippet that displays a chart with dimensions of 500x500. However, I only want to show half of the chart, like 500x250. But whenever I adjust the values in the div, it resizes the entire chart instead of just showing half. My goal is to hide ...

Using AJAX to remove data from a database

My PHP code snippet is displayed below: AjaxServer.php include '../include/connection.php'; // Check for the prediction if(isset($_POST["delete_me"]) && $_POST["delete_me"]=="true"){ $id = $_POST["id"]; $table = $_POST["table"]; ...

Step-by-step guide on populating input fields with JSON data for each row

As a beginner in Programming, I have been searching for an answer to the following problem on this site for days but haven't been able to figure it out yet. To explain briefly, there will be an input form where the user can define the number of rows ...

How come I am unable to expand a collection of objects using Zustand?

I am currently utilizing Zustand in a TypeScript Next.js application. Strangely, whenever I attempt to loop through my state object, I encounter a runtime error message. The structure of the damaged zone object for my car is as follows: const damagedZones ...

Click event dynamically bound to list items

I have a web application built with Durandal and Knockout. Here is the HTML code snippet: <ul id="header"> </ul> In a JavaScript function, I am dynamically adding a list item as follows: $("#header).append('<li id="btn"><a hre ...

Highcharts introduces shared tooltips for specific data series

I am seeking to implement specific behavior in highcharts regarding tooltips. The desired setup includes having two types of tooltips: the default shared tooltip a custom tooltip For the custom tooltip, a simple formatter can be utilized. However, the c ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

Project in Three.js where the camera remains focused on the object while in a top-down perspective

I am currently working on developing a top-down game using Three.js, inspired by classic arcade games like Frogger. I am facing challenges in ensuring that the camera stays centered on the main character as it moves across the screen. I am currently util ...

Utilizing jQuery to Perform Calculations with Objects

Can someone help me with a calculation issue? I need to calculate the number of adults based on a set price. The problem I'm facing is that when I change the selection in one of the dropdown menus, the calculation doesn't update and continues to ...

Determine the width of a dynamically generated div element in JavaScript using the createElement method

Currently, I am utilizing the JavaScript function createElement to generate a new div element and then assigning its innerHTML. Following that action, I am attempting to determine the necessary width required to display the div with all of its content. var ...

Issue with parsing an empty array in a Discord bot built with Node.js

Within this API, there exists an empty array marked with a red underline. Sometimes it's void of content, but other times it contains data. My goal is to display Item Spells: there are no effects on this item. when the array is empty. However, instead ...

Is there a way to use HTML and JS to draw custom lines connecting elements?

Sorry if this question has been asked before. Is there a way to create straight lines connecting HTML elements with just HTML and JavaScript, without relying on SVG or Canvas? If so, what would be the most effective approach? ...

Using asynchronous methods to import a Node.js module

I am attempting to asynchronously load 2 modules due to some issues I encountered. The first module loads and creates a database connection (which takes some time) The second module uses the created connection to handle sessions using express-sessions. ...

Saving data inputted in a form using ReactJS and JavaScript for exporting later

What is the best way to save or export form input in a ReactJS/JS powered website? For example, if I have a form and want to save or export the data in a format like CSV after the user clicks Submit, what method should I use? Appreciate any advice. Thank ...

Record all GraphQL responses using Express

After successfully implementing logging for GraphQL errors using the provided code: app.use('/graphql', graphqlHTTP(request => { return { schema, rootValue: { request }, formatError: error => { const params = ...

Utilizing the power of $.ajax() to parse through an XML document

I have a query about working with a large XML file containing 1000 nodes. Here is the code snippet I am using: $.ajax({ type: "GET", cache: false, url: "someFile.xml", ...