我的主JS中有以下代码:
app.service('portfolioData', function($http, LoginData, Config) {
return {
load: function() {
return $http({
method: 'GET',
url: getHostnamePort(Config) + '/rest/api/property/list',
headers: {
'Content-Type': 'application/json',
'x-api-token': LoginData.apiToken,
'x-api-user': LoginData.apiUser
}
}).then( function successCallback( response ) {
console.log( "Portfolio loaded" );
return response.data;
}, function errorCallback ( response ) {
console.log( "Portfolio load FAILED" );
console.log( response.status );
if ( response.status == '401' )
$scope.failureMessage = "Unauthorised. Please Login in.";
return null;
});
}
};
});
...
app.config(function ($routeProvider) {
...
"http://xxxx/~matthew/view/portfolio.view", resolve: { portfolio: function(portfolioData) { return portfolioData.load(); } }});
});
我的目标Controller(在portfolio.view中声明)因此声明:
app.controller('PortfolioCtrl', [ '$scope', '$http', '$mdDialog', 'LoginData', 'pageData', 'Config', 'portfolio', function ($scope, $http, $mdDialog, LoginData, pageData, Config, portfolio) {
pageData.setTitle( "Portfolio" );
$scope.portfolio = portfolio.result;
$scope.portfolioFailed = false;
解析在路由端正常工作,我可以看到后端调用获取数据,但是当它呈现视图时,我得到:
我知道可能存在某种范围问题,但文档含糊不清,我跟随的示例(https://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx)表明我已正确设置它。
答案 0 :(得分:0)
这里有一个问题。您必须在HTML视图中将控制器定义为ng-controller="PortfolioCtrl"
,但如果您通过ui-router
定义控制器,resolve
将不会注入那些ng-controller
d依赖项。
因此,您只需要在状态配置中定义控制器:
.state('xyz', {
templateURL: "http://xxxx/~matthew/view/portfolio.view",
resolve: {
portfolio: function(portfolioData) { return portfolioData.load(); }
},
controller: 'PortfolioCtrl' // <<=== you need to define it here
});