如果有一个应用程序控制器。在此控制器中,我称为“ saveGame”的资源服务。saveGame具有一个称为“ resolved”的属性。我用false初始化此属性。当promise解析(加载保存游戏)时,我将resolveed属性设置为true。
以上部分的作品。
现在,我在MainCtrl中注入saveGame服务。如果我在本地运行代码,那么它可以工作,因为saveGame几乎可以立即解析。但是,如果我打开延迟-模拟非常慢的连接。saveGame无法及时解决,我需要等待。
这是我的代码:
application
.controller('MainCtrl',
['$scope', 'saveGame', function ($scope, saveGame) {
'use strict';
// At this point the savegame should be resolved
// If not we need to wait for it.
$scope.$watch(saveGame.resolved, function ( newVal, oldVal) {
console.log( newVal + '-' + oldVal ); // #1
if(newVal !== undefined ){
//do your stuff here...
console.log("do your stuff"); // #2
}
});
因此,#1处的newVal,oldVal以未定义的形式出现。#2的控制台日志从不触发。
为了完整起见,我的saveGame服务如下所示:
application
.factory('saveGame',
['$resource', 'config', function ($resource, config) {
'use strict';
var _resolved = false;
var _location = {};
var _load = function (playerId) {
var res;
if (config.getSetting('use-mockup')) {
// Use mockup data
// $resource returns a class representation
res = $resource('data/mockup/savegame/player:id.json');
} else {
// TODO: Use real API
}
// This will return a promise!
return res.get({id: playerId}).$promise;
};
var _save = function (stuff) {
return stuff;
};
return {
load: _load,
save: _save,
location: _location,
resolved: _resolved
};
}]);
而我的appCtrl中的部分是这样的:
// Load the savegame resource
var promise = saveGame.load(1); // PlayerId
promise.then(function (resource) {
// savegame resource was loaded and resolved
saveGame.location = resource.location;
saveGame.resolved = true;
});
所以我知道我做错了什么,但我不知道该怎么办?同样的帮助将不胜感激。
你需要这个:
$scope.$watch(function () { return saveGame.resolved; }, function ( newVal, oldVal) {
console.log( newVal + '-' + oldVal ); // #1
if(newVal !== undefined ){
//do your stuff here...
console.log("do your stuff"); // #2
}
});
您必须将字符串用作带有返回值的watch或function的第一个参数。如果使用字符串“ abc”,则AngularJS比较将$scope.a.b.c
在当前循环和下一个循环中进行比较。如果在那里使用函数,AngularJS将比较函数的结果。
可能更好的方法是更新saveGame
服务并在其中返回承诺。在需要saveGame结果的任何地方,都将使用以下代码:
module.factory('saveService', ['$http', function ($http) {
return {
doSave: function () {
return $http.get(params);
}
}
}])
module.controller('MainCtrl', ['saveService', function (saveService) {
saveService.doSave().then(function onSuccess() {
// handle something after save
});
}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句