我在AngualrJS用户服务,目前正在返回一个承诺:
I have a user service in AngualrJS that currently returns a promise:
getData: function() {
return Restangular.one('users', id).get({single: true});
},
我要添加到返回缓存用户的能力,但不认为我可以做到这一点作为其中一个返回的承诺和其他收益的实际数据:
I want to add the ability to return the cached user, but don't think I can do this as one returns a promise and the other returns the actual data:
getData: function() {
if !data
return Restangular.one('users', id).get({single: true});
else
return data
},
什么是处理这个问题的最佳方式?
What is the best way to handle this?
谢谢!
您应该修改code如下总是返回一个承诺
You should modify your code as below to always return a promise
getData: function() {
var deferred = $q.defer()
if !data
Restangular.one('users', id).get({single: true}).then(function(data){
deferred.resolve(data);
});
else
deferred.resolve(data);
return deferred.promise;
},