AngularJS:如何通过控制器中的服务方法传递id

AngularJS: How to pass the id through a service method in the controller

本文关键字:方法 服务 id 何通过 控制器 AngularJS      更新时间:2023-09-26

我正在开发一个AngularJS web应用程序。我有以下路由配置:

  $routeProvider.
    when("/drivers", {templateUrl: "partials/drivers.html", controller: "driversController"}).
    when("/drivers/:id",{templateUrl: "partials/driver.html", controller: "driverController"}).
    otherwise({redirectTo: '/drivers'});
}]);

为了传递JSON的ID,我在service.js文件

中使用以下方法
F1API.getDriverDetails = function(id) {
        return  $http({
            method: 'JSONP', 
            url: 'http://localhost:8000/app/data/' + id + '/driverStandings.json?callback=JSON_CALLBACK'
        });
    }
    F1API.getDriverRaces = function(id) {
        return  $http({
            method: 'JSONP', 
            url: 'http://localhost:8000/app/data/' + id + '/results.json?callback=JSON_CALLBACK'
        });
    }
    return F1API;
  });

但现在我被困住了。我需要这个方法在一个对象中分配一个车手和他的比赛。但我需要id,所以我在controller.js

/* Driver controller */
controller('driverController', function($scope, $routeParams, F1APIservice) {

    $scope.id = $routeParams.id;
    $scope.races = [];
    $scope.driver = null;
    F1APIservice.getDriverDetails(id).success(function(response){
      $scope.driver = response.MRData.StandingsTable[0].DriverStandings[0];
    });
    F1APIservice.getDriverRaces(id).success(function(response){
      $scope.races = response.MRData.RaceTable.Races;
    });
});

Id是未知的,而我建立我的web应用程序。我做错了什么?

在您的控制器中,您将$routeParams.id分配给$scope.id,但随后您仅使用id调用getDriverDetailsgetDriverRaces,这是未定义的。您需要像这样调用它们:getDriverDetails( $scope.id ) .

更好的方法是将控制器与$routeParams解耦。要实现这一点,使用$routeProviderresolve功能:

$routeProvider.
    when("/drivers/:id", {
        templateUrl: "partials/driver.html",
        controller: "driverController",
        resolve: {
            'id': function($route) {
                return $route.current.params.id);
            }
        }
    })
使用上面的代码,Angular将使id对你的控制器可用:
controller('driverController', function($scope, id, F1APIservice)

由于resolve是承诺感知的,一种替代方法甚至可以在resolve:

中进行服务调用。
$routeProvider.
    when("/drivers/:id", {
        templateUrl: "partials/driver.html",
        controller: "driverController",
        resolve: {
            'driver': function($route, F1APIservice) {
                return F1APIservice.getDriverDetails($route.current.params.id);
            }
            'races': function($route, F1APIservice) {
                return F1APIservice.getDriverRaces($route.current.params.id);
            }
        }
    })

driverraces被注入控制器:

controller('driverController', function($scope, driver, races, F1APIservice)