javascript - Angular 的 $http 中返回的 Promise 与普通 Javascript (ES6) 中返回的 Promise 相同吗?

标签 javascript angularjs http ecmascript-6 angular-promise

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

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

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

我刚刚开始研究 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 block 中的 this 实际上是 Window !(!?) 如何在其中调用 AuthController 类的 setToken() 函数? 我应该使用普通的 Javascript Promise 吗?那么范围会有所不同吗?

我应该怎么做才能兑现 promise ?

最佳答案

这更多的是一个this引用问题。但为了回答你原来的问题,Angular 的 $http 返回一个 $q promise ,这与 ES6 的 promise 不同。

查看 @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
    });

关于javascript - Angular 的 $http 中返回的 Promise 与普通 Javascript (ES6) 中返回的 Promise 相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31420338/

相关文章:

javascript - 如何返回模板/html 页面并 promise 该页面上的函数返回值

javascript - 在 AngularJS 1.6 中悬停时在 md-select/md-options 上显示图像/背景

javascript - 从远程服务器获取一个 JSON 文件(包含希伯来语值)并在 Node.js 中解析它

html - 发布 html 表单数据重定向

rest - 同时使用 HTTP 和 WebSockets 时的 API 命名约定

javascript - Javascript 中的年龄(+闰年)计算?

javascript - RequireJs 定义默认 deps

javascript - 在 Protractor 中返回 bool 值而不是成功失败

javascript - 当我加载 .xml 文件时,它的内容有时会出现在我的网页上,但当我刷新时,它就会消失。 (javascript、jquery、ajax、xml)

javascript - Angular 插入的 HTML 未附加到 Controller