问题描述
我的$ routeProvider中有三个resolve promise函数.我的问题是我可以在加载函数中使用getData函数来获取HTTP请求响应吗?
I have three resolve promise function inside my $routeProvider. My question is that Can I use getData function inside load function for example to get HTTP request response!
角度还会等待getData完成然后加载吗?是在按顺序做它们并等待诺言吗??
Also will angular wait for getData finish then goes to load? Is it doing them in order and waiting for the promises!?
$routeProvider.when = function(path, route) {
route.resolve = {
getData: ['$http', function ($http) {
var http = $http({
method: 'POST',
url: 'a URL',
data: {
route: "/something"
},
headers: {
'something': 'anything'
}
});
return http;
}],
load: [
'getData',
function(getData) {
console.log(getData);
// I'm Actually returning a promise here so no problem at all.
}
],
prefData: [
'$preflightService',
function($preflightService) {
console.log('Preflight Run');
return $preflightService.run();
}
],
};
return originalWhen(path, route);
};
使用上面的代码,我在控制台中收到此错误
Using this code above I get this Error in Console
Error: [$injector:unpr] http://errors.angularjs.org/1.4.12/$injector/unpr?p0=getDataProvider%20%3C-%20getData
我该怎么办?!
我应该以某种方式定义提供商吗??
Should I define a provider somehow!?
推荐答案
每个解析都是异步解析的.如果您希望由"getData"返回的数据用于解决加载"请求,请使其成为单个解决方案,如下所示:
Each resolve is resolved asynchronously. If you want the data returned by 'getData' for resolving the 'load' request, make it a single resolve, something like this:
loadData: ['$http', function($http) {
return $http({
method: 'POST',
url: 'a URL',
data: {
route: "/something"
},
headers: {
'something': 'anything'
}
}).then(function(response){
// getData result available here
return // Return the load promise here
});
}
如果需要,您可以将成功处理程序(.then(function(){})
附加到加载承诺,并返回一个既包含getData结果又包含诸如
If needed, you can attach a success handler (.then(function(){})
to the load promise and return a custom object containing both getData results and load results like
return {
getData: getResp,
loadedData: loadResp
}
它将在控制器中可用.
这篇关于在另一个内部使用$ routeProvider resolve函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!