【问题标题】:Can't call methods inside catch or then of a Promise call无法在 catch 或 Promise 调用中调用方法
【发布时间】:2016-06-08 05:12:46
【问题描述】:

我有一个方法可以返回一个类似的承诺:

    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 与其他文件在同一个文件中,并且在其他地方可以正常工作(不是承诺调用)

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

不能这样做吗?

【问题讨论】:

    标签: promise angular es6-promise ionic2


    【解决方案1】:

    使用箭头函数

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

    【讨论】:

      【解决方案2】:

      改用粗箭头函数

      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)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-24
        • 2016-03-26
        • 2017-02-17
        • 2013-02-28
        相关资源
        最近更新 更多