user1665355 user1665355 - 2 months ago 22
AngularJS Question

How to use $routeParams in resolve

I use

$routeParams
like this right now:

My factory function:

angular.module('fifaApp')
.factory('FifaService', ['$http',
function($http) {
var sdo = {
getTeamDetails: function(code) {
var promise = $http.get('api/team/' + code);
promise.success(function(data, status, headers, conf) {
return data;
});
return promise;
}
}
return sdo;
}
]);


Controller function:

.controller('TeamDetailsCtrl',
['FifaService','testt',
function(FifaService,testt) {
var self = this;
self.team = testt.data;
}
]);


config:

angular.module('fifaApp', ['ngRoute'])
.config(function($routeProvider) {
.when('/login', {
templateUrl: 'views/login.html'
})
.when('/team/:code', {
templateUrl: 'views/team_details.html',
controller:'TeamDetailsCtrl as teamDetailsCtrl',
resolve: {
testt: ['$routeParams','UserService',
function($routeParams, UserService) {
return FifaService.getTeamDetails($routeParams.code);
}]
}
});
$routeProvider.otherwise({
redirectTo: '/'
});
});


But
views/team_details.html
does not show. Any ideas?
Best Regards

Answer

Calllback function don't have an ability to return data. Your ‘getTeamDeatails‘ method should return a promise insteaf of using callbacks, for that you need to return ’$http.get ’ which already returning promise object.

 getTeamDeatails: function() {
      var promise = $http.get('api/team');
      promise.then(function(resp){
        return resp.data;
      });
      return promise;
 }

Add missing FifaService dependency in resolve method

Resolve

resolve: { 
  testt: ['$routeParams', 'FifaService', 
    function($routeParams, FifaService ) { 
        return FifaService.getTeamDetails($routeParams.code); 
 }]
Comments