Jack
Jack

Reputation: 23

Why is $routeParams undefined?

I am trying to use a service to handle an http request:

angular
    .module('app')
    .factory('stats', function($http){
            return {
                getStats: function(path) {
                    return $http
                       .get(path)
                       .then(function(result) {
                            //resolve the promise as the data
                            return result.data;
                        });
                }
            };
    });

When the getStats method is called in the controller however, the $routeParams property is undefined so the request never runs:

app.controller('ChartController', ['$route', 'stats', '$scope', '$rootScope', '$routeParams', function($route, stats, $scope, $rootScope, $routeParams) {

  console.log($routeParams);

  var path = "/players/players/" + $routeParams.playerId;

  var players = stats.getStats(path);

This isn't a problem I experience when I simply run the http request directly in the controller, without using a service.

Upvotes: 1

Views: 341

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

As you said that there was no problem without the service which means the problem is not with the routeParams, but with the way you are handing your service. The problem is the async behavior of AJAX calls. The response is returned prior to response received. There are many ways to fix this. I am going to explain one possible way.

Update your factory to

angular.module('app')
        .factory('stats', function($http){
            return{
                getStats: function(path) {
          return $http.get(path);
        }
            };
        });

Update controller as

var players;
stats.getStats(path).then(function(response){
      players = response.data;
});

Other possible options can be using $q service or using callback functions.

Upvotes: 1

Related Questions