【问题标题】:Is the Promise returned in Angular's $http the same as one in vanilla Javascript (ES6)?Angular 的 $http 返回的 Promise 与 vanilla Javascript (ES6) 中返回的 Promise 是否相同?
【发布时间】:2015-07-15 02:08:26
【问题描述】:

只是一个关于 Promises 和 Angular 的新手问题...

当使用 AngularJS 的 $http 执行 PUT 或 POST 并返回 Promise

这是 chrome 控制台中的 Promise {$$state: Object} - 这与我可以在不使用 Angular Docs 中列出的 .success(function(){...}).error(function(){...}); 的情况下解决的 Promise 相同吗?

我刚刚开始研究 ES6,并决定使用 Babel 编写这个应用程序(这可能与问题无关)。 基本上我在尝试在成功回调中调用 Controller 函数时遇到了这个问题。 这是我的代码的 sn-p:

class AuthController {
constructor ($timeout, $state, $http, apiService) {
    'ngInject';

    this.$http = $http;
    this.$state = $state;
    this.apiService = apiService;
}

setToken (user) {
    // set the token
}   

login () {
    var req = {
     method: 'PUT',
     url: this.apiService.apiHost + '/customers/login',
     headers: {
       'Authorization': undefined
     },
     data: { email: this.email, password: this.password }
    }
    this.$http(req)
    .success(function(data){
      this.setToken();
    })
    .error(function(data){
      // handle it
    });     

但是,.success 块内的 this 实际上是 Window !(!?) 如何在其中调用我的 AuthController 类的 setToken() 函数? 我应该使用普通的 Javascript Promise 吗?那么范围会不一样吗?

我应该如何处理承诺?

【问题讨论】:

    标签: javascript angularjs http ecmascript-6 angular-promise


    【解决方案1】:

    这更像是一个this 参考问题。但要回答您最初的问题,Angular 的 $http 返回一个 $q 承诺,这与 ES6 的承诺不同。

    查看@atinder 的解决方案来解决您的问题,或者您也可以使用arrow functions

       var req = {
         method: 'PUT',
         url: this.apiService.apiHost + '/customers/login',
         headers: {
           'Authorization': undefined
         },
         data: { email: this.email, password: this.password }
        }
        this.$http(req)
        .success((data) => {
          this.setToken();
        })
        .error((data) => {
          // handle it
        });
    

    【讨论】:

    • 非常感谢!它奏效了 :) 我现在很喜欢那些箭头功能哈哈
    【解决方案2】:

    为了在回调函数中使用它,您需要像这样将它bind 传递给函数。

    .success(function(data){
      this.setToken();
    }.bind(this));
    

    另一种方法是将其分配给其他变量,例如

    var self = this;
    

    然后在你的回调中

    .success(function(data){
      self.setToken();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-17
      • 2018-03-12
      • 2017-10-31
      • 2020-04-16
      • 2015-05-18
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多