Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't call methods inside catch or then of a Promise call

I have a method which returns a promise like:

    checkLogin(credentials) {
        return new Promise((resolve, reject) => {
            this.http.post(url, credentials)
                .map(res => res.json())
                .subscribe(
                data => {
                    resolve(data);
                },
                err => {
                    reject(err);
                }
            );
        }); 
    }

I call this method inside another:

    login(credentials) {
        this.checkLogin(credentials)
            .then(function(result) {
                console.log("ok: ",result);
                this.doAlert("ok");
            })
            .catch(function(err) {
                console.log("error: ",err.message);
                this.doAlert(err.message)
            });
}

Here is where the error happens, it is said "TypeError: this.doAlert is not a function":

enter image description here

But the doAlert is in the same file than the others, and it works fine from other places (not promises calls)

    doAlert(text) {
        let alert = Alert.create({
            title: 'Alert;,
            subTitle: text,
            buttons: ['Ok']
        });
        this.nav.present(alert);
    }

Is it not possible to do this?

like image 621
Asenjo Avatar asked Nov 30 '22 23:11

Asenjo


1 Answers

Use fat-arrow functions instead

login(credentials) {
    this.checkLogin(credentials)
        .then((result) => {
            console.log("ok: ",result);
            this.doAlert("ok");
        })
        .catch((err) => {
            console.log("error: ",err.message);
            this.doAlert(err.message)
        });
}

to keep the scope

See also
- https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
- https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript
- What's the meaning of "=>" in TypeScript? (Fat Arrow)

like image 194
Günter Zöchbauer Avatar answered Dec 04 '22 06:12

Günter Zöchbauer