Matt Robinson
Matt Robinson

Reputation: 65

AngularJS Declared Service not being found in $routeProvider resolve functionality

I have the following AngularJS code in my main JS (LoginData is a global value, and Config is a factory instance):

app.service('portfolioData', function($http, LoginData, Config) {
return {
    load: function( $http, LoginData, Config ) {
        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;
        });
    }
};
});

Further down I've declared my routes:

app.config(function ($routeProvider) {
    ...
    $routeProvider.when('/portfolio', {templateUrl: "http://xxxxx/~matthew/view/portfolio.view", resolve: { portfolio: portfolioData.load( $http, LoginData, Config ) }});
});

For some reason AngularJS cannot find the portfolioData service and so will not run the app.

I have tried using a factory instead. It seems to work if I inline the $http call, but I'd rather not inline this code as it is substantial and I wish to reuse it elsewhere.

enter image description here

Upvotes: 0

Views: 25

Answers (2)

joseph oun
joseph oun

Reputation: 135

Did You load the service script before the config? if not do so.

Upvotes: 1

Striped
Striped

Reputation: 2548

First of all, you have no need to pass the services as parameters of your function load:

load: function() {
    return $http({...}).then...
}

Then, I think the portfolio property of the resolve needs a function like :

resolve: { 
    portfolio: function(portfolioData) {
         return portfolioData.load();
    }
}

or resolved:

resolve: { 
    portfolio: function(portfolioData) {
         return portfolioData.load().then(function (data) {
              return data;
         });
    }
}

Upvotes: 1

Related Questions