我想知道,我是否可以将resolve参数注入到另一个resolve参数中。代码会告诉你更多:
.state('videos.videosLection', {
url : '/:lection',
templateUrl : '/partials/videosLection.html',
controller : 'VideosLectionCtrl',
menuItem : 'Videos',
resolve : {
selectedLection : function ($stateParams, lections) {
...
},
sections : function(Section, selectedLection) {
...
}
}
})我使用angular UI-router进行路由。在开始解析部分之前,我需要有selectedLection。
有什么想法吗?非常感谢
发布于 2013-12-20 23:03:16
你能把selectedLection片段变成一项服务吗?然后做这样的事情:
resolve: {
sections: function(Section, selectedLectionService, $stateParams, lections){
var result = selectedLectionService($stateParams, lections);
// do something with result here...
}
}我不知道这是否能满足您的所有需求,但也许它会让您找到正确的方向。如果它不起作用,请告诉我。
发布于 2013-12-30 21:20:45
我终于弄明白了,这里的方法是只解析一个对象,它有几个属性,这些属性本身就是promises。查看代码:
resolve : {
data : function($stateParams, lections, Video, Section, $q) {
// defer for the data object
var defer = $q.defer();
// selectedLection
var selectedLection = null;
// if there is lection selected
if($stateParams.lection)
{
// lection is selected
lections.forEach( function(lection)
{
// find the selected lection
if(lection.addressUrl == $stateParams.lection)
{
// save it
selectedLection = lection;
}
});
}
else
{
// resolve it with everything empty
defer.resolve({
selectedLection : null,
lectionVideos : [],
sections: []
});
return defer.promise;
}
// promise to the lection videos
var deflectionvideos = $q.defer();
// find all the videos by the lection id
Video.GetAllByLection(selectedLection.id, null, function(data) {
// resolve it with the data
deflectionvideos.resolve(data);
}, function(error) {
// resolve it with empty array
deflectionvideos.resolve([]);
});
// promise for the sections
var defsections = $q.defer();
// find all the sections of selected lectino
Section.GetAllByLection(selectedLection.id, function(data) {
// resolve it with the data
defsections.resolve(data);
}, function(error) {
// resolve it with empty array
defsections.resolve([]);
});
// wait, untill all the promises for sections and lectionsvideos are resolved
$q.all([
deflectionvideos.promise,
defsections.promise
]).then(function(data) {
// resolve it with actual data
defer.resolve({
selectedLection : selectedLection,
lectionVideos : data[0],
sections: data[1]
});
});
// return promise for the data object
return defer.promise;
}
}如果你们有其他方法或更好的解决方案,请让我知道:-)
希望它能帮助到某人
https://stackoverflow.com/questions/20703567
复制相似问题