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

Including a personalized User-Agent string in my headers for fetch requests

Currently, I am utilizing the fetch API within my React project to retrieve data from a JSON endpoint. One requirement I have is to include a custom User-Agent string in my requests. Upon inspecting my requests, I noticed that the UA string displays as: ...

beforeSend method in jquery ajax synchronously calling

One of my functions is called: function callAjax(url, data) { $.ajax( { url: url, // same domain data: data, cache: false, async: false, // use sync results beforeSend: function() { // show loading indicator }, ...

HTML control for adjusting the pan and tilt of a device

I'm looking to develop an interactive input where users can drag a dot within a box and see the 2D coordinates of that dot displayed. The goal is to use this feature to control pan and tilt values. A similar functionality from another application is s ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

Unable to start store from localStorage during App initialization

Having trouble setting up my Vuex store with the logged-in user's account details from localStorage. I've looked at numerous Auth examples in Nuxt, but none explain how to retrieve an authToken from localStorage on the client side for subsequent ...

Issues with the audio on ExpressJS video streaming can be quite vexing

After multiple attempts to run an ExpressJS web server that serves videos from my filesystem, I've encountered a frustrating issue. Whenever a video is played, there are constant popping sounds and eventually the audio cuts out completely after 3-10 m ...

Performing an axios request using form data in a React JS application

I am trying to figure out how to use axios in react js to make a cURL request that is currently working. Here is the cURL request: curl -k --request GET "BASE_URL_SERVER/sendText" --form "user_id='uidxxxx'" --form "sign_id=" Every time I try to ...

Retrieving the object ID of an Open Graph from a page's URL

Is there a way to obtain the Facebook Object ID associated with a page directly from the page itself? For instance, if I requested the Object ID 325186347604922, this is what I received: <pre> { "url": ".../ricetta-bigne_salati.htm", "type": " ...

Exploring data elements using iteration in JavaScript

Here is some code that is functioning properly: Morris.Bar({ element: 'barchart', axes: true, data: [ json.bar.bar1 ], xkey: 'x', ykeys: ['y', 'z', ' ...

Tips for eliminating additional white space within a bootstrap row

I'm having trouble removing the extra space on my website while using Bootstrap 5. I've tried various Bootstrap classes like pr-0, mr-0, p-auto, m-auto but none of them seem to work. I also attempted using CSS margin-right: 0; but that didn' ...

"Encountered npm error: JSON input ended unexpectedly" while trying to install express-mysql-session"

I'm currently developing a nodejs project that uses passportjs for user authentication and mysql as the database. I'm now looking to incorporate session storage by utilizing the ""express-mysql-session" package. However, when attemptin ...

When running the command "npx create-next-app@latest --ts," be aware that there are 3 high severity vulnerabilities present. One of the vulnerabilities is that "node-fetch

Just set up a fresh project with Next.js and TypeScript by following the documentation using npx create-next-app@latest --ts. Encountering multiple high severity vulnerabilities despite running npm audit fix --force, which actually adds more vulnerabiliti ...

Tips on running methods consecutively within ngOnInit in Angular

I'm currently working on an ngoninit function that contains four methods. Two of these methods are responsible for retrieving data from the API, while the other two are intended to load this data when the page loads. ngOnInit(){ getname(); getsubjects ...

Update the HighChart Pie chart depending on the selection in the dropdown menu

Currently, I am working on creating a pie chart using data retrieved from a web socket in JSON format. Once the JSON object is returned, if the user selects the "Pie Chart" option, another Select dropdown will be displayed to choose a specific time period. ...

What methods can Ajax utilize to make asynchronous requests and receive synchronous responses?

While using jQuery ajax to send a request to a web service, I came across an interesting bug: var AjaxResult; login = function () { AjaxResult = ""; $.ajax({ type: "POST", url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlanne ...

Comparison between bo-html and bo-text

As I was going through the documentation for the bindonce directive, a question popped into my head regarding the distinction between bo-html and bo-text. bo-html: This evaluates "markup" and displays it as HTML within the element. bo-text: ...

The logo image dynamically switches as the user scrolls through various colored sections

Looking to create a feature that changes the logo image as users scroll through different colored sections. Specifically, switching between dark and light themes. a) How can we determine if the section the user is currently on has a dark or light theme? b ...

display and conceal a division by clicking a hyperlink

How can I make a hidden div become visible when clicking on a specific link without using jQuery? Javascript function show() { var a = document.getElementsByTagName("a"); if (a.id == "link1") { document.getElementByID("content1").style.v ...

Is there a way for me to properly initiate the Material UI Modal from the parent component?

This is the main component: import React from 'react'; import ChildModal from 'ChildModal'; const MainComponent = () => ( <div> <span>Click </span> <a>HERE TO OPEN MODAL</a> <div> ); ...

Sending an incorrect value to the data variable

Apologies for my limited proficiency in English, Hello, I am new to Vue and struggling with an issue that I can't seem to resolve. I am fetching art data from an API (a simple list of dictionaries), and then creating a multi-array structure (list of l ...