为什么$routeParams没有定义?

Why is $routeParams undefined?

本文关键字:定义 routeParams 为什么      更新时间:2023-09-26

我正在尝试使用服务来处理http请求:

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;
                        });
                }
            };
    });

当在控制器中调用getStats方法时,$routeParams属性是未定义的,因此请求永远不会运行:

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);

当我直接在控制器中运行http请求而不使用服务时,这不是我遇到的问题。

正如你所说,没有服务就没有问题,这意味着问题不在于routeParams,而在于你处理服务的方式。问题在于AJAX调用的异步行为。在收到响应之前返回响应。有很多方法可以解决这个问题。我将解释一种可能的方法。

更新你的工厂到

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

更新控制器为

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

使用$q服务或使用回调函数是其他可能的选择