Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access class variable inside Promise then() function? [duplicate]

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?

like image 628
Suroor Ahmmad Avatar asked Jan 02 '18 16:01

Suroor Ahmmad


1 Answers

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.

like image 77
Günter Zöchbauer Avatar answered Oct 15 '22 10:10

Günter Zöchbauer