只是一个关于 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/