Attempting to grasp the concept of Promises in Angular 2

I have encountered an issue while working with the Google API service and I am stuck at the promise response stage. Here is the code snippet for reference:

getPromise: Promise<any>;
loadSheets: Array<any>;

constructor(public _checkAuthApiService: CheckAuthApiService) { }

ngOnInit() {
    if (this._checkAuthApiService) {
        this._checkAuthApiService.checkAuth().then(res => {
            if (res && !res.error) {
                this.loadSheetsFunc();
            }
        });
    }

    //setTimeout(function(){},1000); //When i add this it works :(
}

loadSheetsFunc = () => {
    this.getPromise = new Promise((resolve: any, reject: any) => {
        resolve(this._checkAuthApiService.loadSheetsApi())
    });
    this.getPromise.then((res: any) => this.sheetsResults(res));
};

sheetsResults = (res: any) => this.loadSheets = res.result.values;

I am unsure about what is causing the issue, but interestingly, when I include a setTimeout within the ngOnInit function, the code starts working and I get the desired data on the view. Can someone provide assistance with this code, or even suggest a better approach using Observables? Thank you in advance.

Answer №1

Using the setTimeout() function triggers a full Angular2 change detection cycle. This action helps Angular2 recognize any updated properties within the code.

If Angular2 fails to recognize the updates without the setTimeout() function, it could indicate a problem with polyfills or their loading order.

If we were to tweak your code slightly:

loadSheets: Array<any>;

constructor(public _checkAuthApiService: CheckAuthApiService) { }
ngOnInit() {
    if (this._checkAuthApiService) {
        this._checkAuthApiService.checkAuth().then(res => {
            if (res && !res.error) {
                this.loadSheetsFunc();
            }
        });
    }
}

loadSheetsFunc() {
    this._checkAuthApiService.loadSheetsApi()
    subscribe(val => this.sheetsResults(res));
}

sheetsResults(res: any) {
    this.loadSheets = res.result.values;
}

It is unclear what the loadSheetsApi() method returns, assuming it is an Observable.

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

A few of the npm packages that have been installed globally are not functioning properly

After installing npm globally, I checked its version using npm -v and it displayed correctly as 7.13.0. Similarly, I installed heroku-cli globally, but when I ran heroku --version, it returned the error message: C:\Users\MyName\AppData&bso ...

Implementing the useEffect hook in React to iterate over JSON data and update the state

Having trouble implementing job location filtering ("remote"/"in-person"/"hybrid") for my personal project. As a beginner in programming, I've spent quite some time troubleshooting the fetchLocationData function and passing URLSearchParams. I anticipa ...

The data shown in the C3.js tooltips

I have successfully created a chart like this on jsfiddle: http://jsfiddle.net/q8h39/111/ The chart includes customized tooltip contents for each plot. I attempted to add extra data to the tooltip using the "indexOf()" method, but unfortunately, it did no ...

Module or its corresponding type declarations not found in the specified location.ts(2307)

After creating my own npm package at https://www.npmjs.com/package/leon-theme?activeTab=code, I proceeded to set up a basic create-react-app project at https://github.com/leongaban/test-project. In the src/index.tsx file of my react app, I attempted to im ...

Troubleshooting Issue with jQuery onclick Function not Transmitting Data

Why is this error occurring: Uncaught TypeError: Object [object global] has no method 'data' HTML: $attributes = array('class' => 'main post', 'onsubmit' => 'validateModules(event)', 'dataid& ...

How can a TypeScript object be declared with a single value assignment to itself?

Whenever I try to declare an object and assign a key to itself, I encounter errors. I have attempted different methods, but the error persists. const a = { d:123, a:a//<-TS2448: Block-scoped variable 'a' used before its declaration. } co ...

Is there a method to introduce a line break for each piece of data that is shown?

I am currently working with an array and have successfully displayed it on the screen. My inquiry is whether it is feasible to insert a line break for each of the data points it presents. { name: "cartItems", label: "Product Name ...

"Could you please help me understand the process of receiving a JSON in an Express

When working with React, I encountered an issue where the JSON data sent to me from the front-end is in a strange format (an object with the data as a string). I am unsure how to convert it back into the object type. This is what I send: const data = { ...

Using Primeng to implement pagination and lazy loading in a dataView

Looking for a way to search through product data with filters and display it using primeng dataview? Consider implementing pagination in your API that pulls products from the database page by page. Set the products array as the value in dataview so that wh ...

Dealing with AJAX errors consistently in jQuery

Is it possible to efficiently handle 401 errors in AJAX calls and redirect to login.html without repeating the same code over and over again? if (xhr.status === 401) { location.assign('/login.html'); } I am seeking a way to manage these erro ...

Is it possible to simultaneously use two $scoped variables within an Angular controller?

Currently, I am developing an angular application that connects to a Rails backend and interacts with the database through API calls to receive JSON objects. My challenge lies in defining multiple scoped variables within a controller. At the moment, I have ...

JavaScript: Transform an Array of Strings into an Array of Objects

Here is an array containing different strings: let myArray : ["AA","BB" , "CC" ...] My goal is to transform it into an array of objects: myArray = [{"id":1 , "value": "AAA"},{"id":2 , "value": "BBB"},{"id":3 , "value": "CCC"}...] I attempted to achiev ...

What steps should I take to address this 'key' alert?

My browser console is displaying the following error message: Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information. ExpenseList@http://localhost:3000/main.cfec1fef7369377b9a ...

Simple JavaScript numeric input field

Hey there, I'm a beginner learning JavaScript. I'm currently working on creating a program that adds numbers input through text fields. If you want to check out the HTML code, visit this link on JS Fiddle: http://jsfiddle.net/fCXMt/ My questio ...

Encountered an ERROR when attempting to deploy a next.js app to Azure Static Webapp using GitHub actions for

I am encountering an issue that is causing some frustration. The problem only arises during my github actions build. Interestingly, when I run the build locally, everything works perfectly and I can access the route handler without any issues. However, eve ...

Populate a chart in real-time with data pulled directly from the Component

I'm completely new to Angular and I feel like I might be overlooking something important. Within my component, I have 3 variables which are populated after invoking the .subscribe method on an observable object. For example: this.interRetard = this ...

Error: The communication channel abruptly closed before the expected response could be delivered

Before diving into the question, I want to mention that the only reference I could find related to this issue was on this Stack Overflow thread. The problem seemed to be associated with Wappalyzer, but it was reportedly fixed in version 4.0.1. Oddly enough ...

Tips for executing a function in the HC-Sticky plugin?

Currently, I am utilizing the HC-Sticky JavaScript plugin and endeavoring to utilize the documented reinit method. However, I am facing difficulty in understanding how to execute it. In this CodePen demo, a basic setup is displayed along with an attempt t ...

Adapt vanilla JavaScript code to be compatible with Node.js, MongoDB, and Express framework

In the midst of working on a blog project for my class, I find myself faced with the challenge of integrating Nodejs, Mongo, and Express into our existing setup. Up until now, we have been gradually transitioning to using Express in our application develop ...

Firebug detected an error with the regular expression flag "h" after executing the YUI Compressor

When I run YUI Compressor, an error occurs with the message: invalid regular expression flag h [Break On This Error] ction(event){$(this).removeClass('lumi...cs_glb.php</b> on line <b>221</b><br/> The issue seems to be with t ...