Issue
I have the following code in my main 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(); } }});
});
And my target Controller (declared in the portfolio.view) is declared thus:
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;
The resolve is working correctly at the route end, and I can see the back-end calls getting the data, but when it goes to render the view, I get:
I know there may be some kind of scoping issue, but the documentation is vague, and an example I’m following (https://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx) suggests I’ve set it up it correctly.
Solution
There is a catch here. You must be defining the controller in your HTML view as ng-controller="PortfolioCtrl"
but ui-router
will not inject those resolve
d dependencies if you define your controller via ng-controller
.
So you need to define your controller in the state configuration only:
.state('xyz', {
templateURL: "http://xxxx/~matthew/view/portfolio.view",
resolve: {
portfolio: function(portfolioData) { return portfolioData.load(); }
},
controller: 'PortfolioCtrl' // <<=== you need to define it here
});
Answered By – Shashank Agrawal
Answer Checked By – Timothy Miller (AngularFixing Admin)