我有这项服务
service.getCurrentUser = function () {
var def = $q.defer();
if (service.user == null)
{
$http.get("./api/GetCurrentUser/")
.success(function(data) {
service.user=data;
def.resolve(data);
})
.error(function() {
def.reject("Failed to get user");
});
}
else
def.resolve(service.user);
return def.promise;
}
在我的控制器中,我想调用它并等待返回,然后如果用户在某个组中,则运行其他代码
我如何编写它以便使用服务返回的承诺
答案 0 :(得分:0)
promise实现可以如下:
service.getCurrentUser = function () {
return new Promise((resolve,reject)=>{
if (service.user == null) {
$http.get("./api/GetCurrentUser/")
.success(function (data) {
service.user = data;
resolve(data);
})
.error(function () {
reject("Failed to get user");
});
}else{
resolve(service.user);
}
});
}
您可以这样称呼它:
service.getCurrentUser()
.then(user => {
console.log('user', user);
})
.catch(error => {
console.log('error', error);
});