【发布时间】:2015-06-05 17:28:27
【问题描述】:
我对 Angular 很陌生,但我正在尝试找出一些东西。
我确实有一个返回承诺的方法:
preloaderServiceObject.Load = function(referencePaths){
var deferred = $q.defer();
$(referencePaths).each(function(index, referencePath) {
var preloadedElement = document.createElement('img');
{
preloadedElement.onload = deferred.resolve;
preloadedElement.src = referencePath;
}
});
return deferred.promise;
}
这一切正常,不会导致问题。 但是,我确实有另一种方法应该在 promise 的完成调用中返回一个 promise,如下所示:
OfficeUIRibbonControlServiceObject.Initialize = function(configurationFile) {
$http.get(configurationFile)
.then(function (response) {
$rootScope.Tabs = response.data.Tabs;
$rootScope.ContextualGroups = response.data.ContextualGroups;
var images = JSPath.apply('.Groups.Areas.Actions.Resource', $rootScope.Tabs);
images.concat(JSPath.apply('.Tabs.Groups.Areas.Actions.Resource', $rootScope.ContextualGroups));
PreloaderService.Load(images);
});
}
最后一行 PreloaderService.Load(images); 确实返回了本文第一个函数中定义的承诺。
但是,现在我想调用 `OfficeUIRibbonControlServiceObject.Initialize' 方法,但是我应该如何更改此方法,以便等待 PreloaderService 的加载完成?
仅仅更改方法以返回该承诺是行不通的,因为返回的对象将是未定义的(因为我在 $http 的 then 方法中。
亲切的问候,
编辑:按照 Rouby 的建议,使用承诺:
初始化函数:
OfficeUIRibbonControlServiceObject.Initialize = function(configurationFile) {
$http.get(configurationFile)
.then(function (response) {
$rootScope.Tabs = response.data.Tabs;
$rootScope.ContextualGroups = response.data.ContextualGroups;
var images = JSPath.apply('.Groups.Areas.Actions.Resource', $rootScope.Tabs);
images.concat(JSPath.apply('.Tabs.Groups.Areas.Actions.Resource', $rootScope.ContextualGroups));
var deferred = $q.defer();
PreloaderService.Load(images).then(function() {
deferred.resolve();
});
return deferred;
});
}
InitializeService 方法:
function InitializeService(serviceInstance, configurationFile) {
serviceInstance.Initialize(configurationFile).then(function() {
console.log('This method has been called.');
});
}
这样的结果是我得到:Error: serviceInstance.Initialize(...) is undefined
【问题讨论】:
-
需要在Initialize函数范围内创建deferred
-
请参阅"Should questions include “tags” in their titles?",其中的共识是“不,他们不应该”!
-
@Rouby 这似乎有效。将deferred的定义放在第一行,在
Load方法的then()函数中解析,然后作为最后一个语句返回。
标签: javascript jquery angularjs