我有一个角度服务从工厂发出一个$http
承诺进行REST调用,效果很好。
var UserService = function($cookies, DataFactory, jsonHelper, $q) {
var USER_KEY = 'user';
var USERNAME_KEY = 'username';
var svcData = {
u: null,
b: null,
}
var service = {
setUser : function(user){
svcData.u = user;
$cookies.put(USER_KEY, user.id);
},
getUser : function(){
if(svcData.u === null){
DataFactory.getPrincipalName().then(function(adata){
DataFactory.getBDUser(adata.data.username).then(function(data){
var reg = {};
jsonHelper.setupRegistry(data.data,
reg);
jsonHelper.resolveReferences(
data.data, reg, 5);
console.log("Request is back");
svcData.u = data.data;
});
});
}
return svcData.u;
}
... snipped ...
在我的控制器中,我这样做:
$scope.$watch($scope.user, function(newUser){
console.log($scope.user);
console.log("USER HERE");
doSomeStuff();
});
$scope.user = UserService.getUser();
问题是当我第一次分配$scope.user
(它为空)时,手表会被触发,然后我收到控制台消息“请求回来了”,但监视功能不会再次触发。
为什么,我该怎么做?
答案 0 :(得分:1)
将字符串传递给$watch()
$scope.$watch('user', ...
newUser
无效时,中断函数(null / undefined)
if (!newUser){
return;
}
使用承诺
转换getUser()
函数以返回promise
。
例如,https://plnkr.co/edit/nzq9O0JMTxn1k7FL9We5
app.service('UserService', function($http, $q, $timeout) {
var cachedUser = null;
return {
getUser: getUser
}
function getUser() {
var def = $q.defer();
if (cachedUser) {
def.resolve(cachedUser)
} else {
// get user from cache. using timeout to simulate http response taking 2.5 seconds
$timeout(function() {
cachedUser = {
name: 'Mr User'
};
def.resolve(cachedUser);
}, 2500);
}
return def.promise;
}
});
例如:
$scope.$watch('user', function(newUser) {
if (!newUser){
return;
}
doSomeStuff();
});
UserService.getUser()
.then(function(user){
$scope.user = user
});