Angular 的 $http 中返回的 Promise 是否与原版 Javascript (ES6) 中返回的相同?

Is the Promise returned in Angular's $http the same as one in vanilla Javascript (ES6)?

只是一个关于 Promises 和 Angular...

的新手问题

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

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

我刚刚开始研究 ES6 并决定使用 Babel 编写这个应用程序(这对问题可能重要也可能不重要)。 基本上我遇到这个是因为我试图在成功回调中调用 Controller 函数。 这是我的代码片段:

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 class 的 setToken() 函数? 我应该使用普通的 Javascript Promise 吗?那么范围会有所不同吗?

我应该如何处理承诺?

为了让这个在回调函数中可用,你需要像这样 bind 它到函数。

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

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

var self = this;

然后在你的回调中

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

这更像是一个 this 参考问题。但是要回答你原来的问题,Angular的$httpreturns一个$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
    });