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

标签 promise angular es6-promise ionic2

我有一个返回 promise 的方法,例如:

    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”:

enter image description here

但是 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
- What's the meaning of "=>" in TypeScript? (Fat Arrow)

关于promise - 无法在 catch 或 Promise 调用中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35627129/

相关文章:

javascript - 去掉 map 功能

javascript - 异步/等待 vs 组合生成器和 promise ?

javascript - 未捕获的语法错误 : await is only valid in async function in async function

javascript - 如何解决递归异步 promise ?

promise - JS fiddle 中的 JavaScript Promises 示例不起作用

javascript - .then 中嵌套的 Promise 在第一个 Promise Node 之前运行

javascript - 为什么 .then() 在没有 JavaScript promise 的情况下工作?

javascript - Angular ,在 html 中找不到元素

javascript - 错误 TS2315 : Type 'ElementRef' is not generic material angular

angular - 尝试使用具有不同模板的相同组件