我正在尝试使用resolve
并将其注入factory
,然后在controller
中打印解析返回的数据。
基本上代码看起来很像:
angular
.module('appRouter',['ui.router'])
.controller('routerCtrl',function(resolveData){
console.log(resolveData);
})
.factory('repoService',function($http){
var API = "https://jsonplaceholder.typicode.com/posts/1";
return {
getResolveData : function($http){
return $http.get(API);
}
}
})
.config(function($stateProvider,$urlRouterProvider){
$stateProvider
.state('settings.profile',{
url:'/profile',
templateUrl:'templates/profile.html'
})
.state('settings.account',{
url:'/account',
templateUrl:'templates/account.html',
controller:'routerCtrl',
controllerAs:'vm',
resolve:{
resolveData : function(repoService){
return repoService.getResolveData().then(function(response){
return response.data;
});
}
}
});
$urlRouterProvider.otherwise('/settings/profile');
});
但代码不起作用。 No error in console but the routing to settings/account does not work . And nothing is printed on the console.
BUT
如果我们在不注入服务的情况下执行此操作,则以下代码可以正常工作。
.state('settings.account',{
url:'/account',
templateUrl:'templates/account.html',
controller:'routerCtrl',
controllerAs:'vm',
resolve:{
resolveData : function(){
var root = 'https://jsonplaceholder.typicode.com';
return $http.get(root+'/posts/1').then(function(response){
return response.data;
});
}
}
});
我无法弄清楚我做错了什么?请解释一下。