AngularJS,从另一个控制器/服务方法访问JSON

时间:2015-09-09 13:20:29

标签: angularjs api service controllers

所以我使用的是API。我创建了一个访问该API的服务,让我们说我们有一个团队控制器,它可以访问团队名称,日期创建及其玩家等团队信息。我们还有一个播放器控制器,它通过我们正在使用的API提供有关玩家的信息。当我打开一个玩家的信息表时,我有他的团队ID。如何使用团队ID访问他的团队名称?我尝试在双花括号中运行一个函数,例如,getTeamName并提供团队ID。浏览器无限次重新加载页面,并向我发送了大量数据包,一次又一次地加载页面。这是一个示例代码:

controllers.js



    myAppControllers.controller('teamController', function($scope, $routeParams, myAPIservice) {
    $scope.id = $routeParams.id; // Team Id

    myAPIservice.getTeam($scope.id).success(function (response) {
        $scope.team = response;
    });

    myAPIservice.getTeamPlayers($scope.id).success(function (response) {
        $scope.players = response;
    });
});

myAppControllers.controller('playerController', function($scope, $routeParams, mundialAPIservice) {
    $scope.id = $routeParams.id; // Player Id

    myAPIservice.getPlayer($scope.id).success(function (response) {
        $scope.player = response;
    });
});




services.js



myAppServices.factory('myAPIservice', function($http) {

  var myAPIservice = {};

    myAPIservice.getTeam = function(team_id) {
      return $http({
        method: 'GET',
        url: 'http://whatever.com/api/team/' + team_id + '?apikey=fff'
      });
    }
    
    myAPIservice.getTeamPlayers = function(team_id) {
      return $http({
        method: 'GET',
        url: 'http://whatever.com/api/players?apikey=fff&teamId=' + team_id
      });
    }

    myAPIservice.getPlayer = function(player_id) {
      return $http({
        method: 'GET',
        url: 'http://whatever.com/api/players/' + player_id + '?apikey=fff'
      });
    }




对不起任何错误,如果我应该提供更多关于我的代码的信息说出来,我就写了这篇帖子。

1 个答案:

答案 0 :(得分:0)

myAppControllers.controller('playerController', function($scope, $routeParams, mundialAPIservice) {
    $scope.id = $routeParams.id; // Player Id

    myAPIservice.getPlayer($scope.id).success(function (response) {
        $scope.player = response;
    });
    //I assume player resoponse contains team id in teamId property .. passing it to getTeam method to get team name
     myAPIservice.getTeam ($scope.player.teamId ).success(function (response) {
        // i am only getting team name but you can other info in response too  
        $scope.player.Teamname = response.Teamname;
    }); 

});

这应该适用于imo。由于您的服务已经getTeam并且服务已经注入。您可以从注入服务的任何控制器访问任何服务方法。