【发布时间】: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