7

I'm working on a Angular4 + PHP website, where i send HTTP requests to the server using Promise, since i want my application to perform routing according to the response of the server. I want to access a class variable inside the then() but it throws undefined() error.

Here is my code:

status = false;

checkUser(): Promise<any>{
// .....
    return this.http
        .get('http://localhost:8000/api/user', this.options)
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError);
}

private extractData(res: any) {
    data = res.json();
    this.status = data.status; // here it throws error undefined 
    return this.status; 
}

Is there any other way to implement this?

Suroor Ahmmad
  • 1,110
  • 4
  • 23
  • 33
  • 3
    Again. Change `this.extractData` to `res => this.extractData(res)`. This question is being asked again and again. – JB Nizet Jan 02 '18 at 16:23
  • 2
    @JB Nizet Yes, I do agree, its been asked quite many times, but as a beginner to angular,typescript its very hard to follow up others code, hope you can understand :) – Suroor Ahmmad Jan 02 '18 at 16:45
  • Sure. I've done this mistake myself. But google is your friend. Googling for the title of your question and clicking on the first few results would have given you the answer. – JB Nizet Jan 02 '18 at 16:47
  • @JB Nizet Thank you! Yeah I'll follow it :) – Suroor Ahmmad Jan 02 '18 at 17:04

1 Answers1

14

If you pass a function reference, this won't point to the local class instance anymore.

You can use bind

.then(this.extractData.bind(this))

or arrow functions

.then((res) => this.extractData(res))

to get the desired behavior.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567