The Angular2 promise resolves before the web service call has finished executing

I have a service in Angular 2 that contains a function responsible for providing data for a dropdown list. This particular function returns a promise.

Below is the code snippet from the service:

getStuff(): Promise<Stuff>
    {
            return this.http.get("http://myserver/myServices/myService.svc/rest/getStuff")
            .map(res => this.dataHandler.extractData(res)).toPromise()
            .catch(err => this.dataHandler.handleHttpError(err));
    }

During a save event, I call this function to update the newly saved data, ensuring that the dropdown list utilizing this data remains current.

The following is the code where I invoke this service:

    ngOnInit()
    {
      this.onSavedSubscription = this.OnSaved.subscribe((data: any) =>
      {
        if (data.IsSuccessful)
        {
            this.myService.getStuff().then(
                res=>
                {
                    this.myService.stuffs = res;
                }
            );
      }
    }

Upon executing the above code, the getStuff function is invoked. However, before it can return the updated data fetched from the database, the execution jumps to "then" and populates this.myService.stuffs with outdated data present in res. This behavior has left me confused. I was under the impression that "then" would only execute after the completion of getStuff and the retrieval of new data. Any assistance would be greatly appreciated.

Answer №1

Upon investigating, I discovered that the root cause of the issue was caching of data. To address this, I made adjustments to the service as shown below:

retrieveData(enableCache: boolean = true): Promise<Data>
{
    if (enableCache)
    {
        return this.http.get("http://myserver/myServices/myService.svc/rest/retrieveData")
            .map(res => this.dataHandler.extractData(res)).toPromise()
            .catch(err => this.dataHandler.handleHttpError(err));
    }
    else
    {
        let headers = new Headers();
        headers.append('Cache-control', 'no-cache');
        headers.append('Cache-control', 'no-store');
        headers.append('Expires', '0');
        headers.append('Pragma', 'no-cache');


        return this.http.get("http://myserver/myServices/myService.svc/rest/retrieveData", { headers: headers })
            .map(res => this.dataHandler.extractData(res)).toPromise()
            .catch(err => this.dataHandler.handleHttpError(err));
    }
}

This modification allows me the flexibility to control whether caching should be applied or not. If there are any suggestions for improvement or a more efficient approach to managing caching, please feel free to leave a comment.

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

What is the appropriate data type to specify for the useLoaderData() function, and in what

I'm currently delving into the deep #6 tutorial on NetNinja's react-router, but I'm attempting to implement it using TypeScript. My task involves fetching data from a JSON object, utilizing the useLoaderData() hook, and trying to properly ma ...

Two paths for a single Angular component

Is it feasible to create two distinct routes that reference one component? Consider the following scenario: { path: 'login', component: LoginComponent }, { path: 'user/:id/login', component: LoginComponent } I'm inquiring about t ...

I'm having trouble getting systemjs to properly connect and download my latest module

Recently, I developed an Angular module that is being downloaded via npm as a private node module in our company registry. Despite setting the default extension to js, my systemjs keeps searching for it in my current directory with any extension. ...

Having trouble compiling a basic application with npm link to access an external library

After attempting to establish a basic component library for consumption by an application and connecting them using npm link, I encountered errors during compilation and am unsure of what steps I may have missed. The structure is minimal, intended solely t ...

Creating a personalized NPM package: Converting and exporting TypeScript definitions

Question: Do I need to adjust my TS configuration or add a TS build step? I recently developed a new npm package: Custom-NPM-Package / - src -- index.js -- index.d.ts -- IType.ts accompanied by this tsconfig.json: { "compilerOptions" ...

FIREBASE_AUTHCHECK_DEBUG: Error - 'self' is undefined in the debug reference

I'm encountering an issue while trying to implement Firebase Appcheck in my Next.js Typescript project. firebase.ts const fbapp = initializeApp(firebaseConfig); if (process.env.NODE_ENV === "development") { // @ts-ignore self.FIREBASE_ ...

Is Angular 2+ responsible for loading the entire module or only the exported components within it?

I'm dealing with a situation where I have a large module but only need to export one specific component. I'm wondering if Angular loads the entire module or just the exported components, as I want to optimize performance without compromising the ...

When any part of the page is clicked, the data on the Angular page will automatically

Clicking the mouse anywhere on the page, even in a blank spot, causes the data array to resort itself. I understand that clicking may trigger a view change if an impure pipe is set, but I have not used one. So I am puzzled because my development testing ...

Angular Chart.js is throwing an error: "Uncaught SyntaxError: Cannot use import statement outside a module"

Upon opening the page, an error in the console related to Chart.js 4.2.1 is being displayed. Description of first image. Description of second image. Is it possible that this issue solely lies with Chart.js? How can it be resolved? To address the proble ...

Issue with installation of Npm package dependencies

I recently created an npm package from a forked repository at https://github.com/pwalczak83/angular2-datatable After changing only the name and version in the package.json file, I installed the package using npm i -S angular2-datatable-custom. However, up ...

Retrieving Names Using Angular2 Dynamic Component Loader to Render a Component List

I am currently utilizing a Dynamic Component Loader to present a series of components using *ngFor: <div [dragula]='"bag-one"' [dragulaModel]='types'> <div *ngFor="let component of types; let i = index"> <dcl-wrapp ...

How to retrieve static attributes while declaring an interface

class A { public static readonly TYPE = "A"; } interface forA { for: A.TYPE } I am facing an issue while trying to access A.TYPE from the forA interface in order to perform type guarding. The error I encounter is: TS2702: 'A' only refe ...

`Why isn't GetServerSideProps being triggered for a nested page in Next.js when using Typescript?

I have been working on a page located at /article/[id] where I am trying to fetch an article based on the id using getServerSideProps. However, it seems that getServerSideProps is not being called at all as none of my console logs are appearing. Upon navi ...

What is the best way to permit multiple instances of a component in separate tabs without losing their individual states?

My application is equipped with a lazy loading tab system that is controlled by a service. When a user chooses an option from the navigation menu, two key actions take place : An entry is appended to the tabs array within the tab service. A new route is t ...

Electron does not have the capability to utilize Google's Speech to Text engine

I am trying to connect my microphone with the Google Speech to Text engine. I came across this page and copied the code into my renderer.ts file, uncommented the lines with const, but when I run it, I encounter an error at line 7 (const client = new speech ...

Implementing express-openid-connect in a TypeScript project

Trying to incorporate the express-openid-connect library for authentication backend setup with a "simple configuration," an issue arises when attempting to access the oidc object from express.Request: app.get("/", (req: express.Request, res: express.Respon ...

Exploring Angular2's ability to interpret directive templates using the ng-container

Recently delving into angular2, I ventured into creating dynamic forms and generating fields by following the guide provided in this URL. The result was as expected. The dynamic form component renders each field one by one using ng-container, like shown b ...

Safari is currently experiencing issues with running the Angular 11 application

Working on my Angular 11 application has been smooth sailing so far when I run (ng serve) in Google Chrome and Firefox. However, I've encountered a problem when trying to access it through Safari 5.1.7. The error message that pops up in Safari is: ...

Discovering the root cause of an Angular binding failure

In my Angular application, I have implemented support for multiple browser tabs using angular-redux @select and {{ property }} bindings. Everything was working fine until I decided to configure my angular store with the redux-state-sync middleware to use b ...

Tips for maintaining consistent column width when scrolling down (column juggling) within a table in your Angular application

Take a look at this preview of the app I'm currently developing. https://stackblitz.com/edit/angular-ivy-3mrzkr In order to handle the large amount of data in my real app, I needed to incorporate a third-party scrolling module. After testing out cdk ...