无法在 catch 或 Promise 调用中调用方法

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

我有一个方法 returns 像这样的承诺:

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

我在另一个里面调用这个方法:

    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)
            });
}

这里是错误发生的地方,据说"TypeError: this.doAlert is not a function":

但是 doAlert 与其他文件在同一个文件中,并且它在其他地方工作正常(不是 promises 调用)

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

这不可以吗?

改为使用粗箭头函数

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)
        });
}

保持范围

另见
- https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
- https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript
-

使用箭头函数

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)
        });