在AngularJS中发出第二个get请求

时间:2013-11-22 21:40:08

标签: javascript angularjs

以下代码有效,我在下面返回了JSON。我感兴趣的是cars_url。如何获取URL (以及最佳方式)然后再发出二次获取请求?

JSON

{
    created: "2013-11-08T18:57:44",
    domain: "www.test.com",
    cars_url: "/api/v1/carlot/4",
    image: null,
    modified: "2013-11-08T18:57:44"
}

的JavaScript

app.factory('CbgenRestangular', function(Restangular) {
    return Restangular.withConfig(function(RestangularConfigurer) {
        RestangularConfigurer.setBaseUrl('http://127.0.0.1:8000');
    });
});


app.controller("CampaignData" ,
               [
                   '$scope',
                   'Restangular',
                   'CbgenRestangular',
                   function($scope, Restangular, CbgenRestangular){
                       CbgenRestangular.one('api/v1/person', "james").get().then(
                           function(person) {
                               $scope.person = person;
                               console.log(person)
                           }
                       );
                   }
               ]);

2 个答案:

答案 0 :(得分:1)

app.controller("CampaignData" , ['$scope', 'Restangular', 'CbgenRestangular', '$http',
    function($scope, Restangular, CbgenRestangular, $http){

        CbgenRestangular.one('api/v1/person', "james").get().then(function(person) {
                $scope.person = person;
                console.log(person);
                var cars = $http({method: 'GET', url:person.cars_url);
                cars.then(function(data){
                     // do success things here
                }, function(data){
                     /do error things here
                });
            }
        );

}]);

如果您有多个级别,嵌套请求可能会变得混乱。在这种情况下,您应该使用$ q来控制请求的流程。

app.controller("CampaignData" , ['$scope', 'Restangular', 'CbgenRestangular', '$http', '$q',
    function($scope, Restangular, CbgenRestangular, $http, $q){
    $scope.person = {cars_url:"your 404 url here"};

    var personcall = CbgenRestangular.one('api/v1/person', "james").get();
    $q.when(personcall.then(
        function(person) {
            $scope.person = person;
            console.log(person);
        }
    ))
    .then(function(){
        var cars = $http({method: 'GET', url:$scope.person.cars_url);
        cars.then(function(data){
             // do success things here
        }, function(data){
             /do error things here
        });
    });
}]);

答案 1 :(得分:1)

如果您想在$scope.person更改时(person请求的响应中发生更改),您可以在控制器中设置$watch

$scope.$watch('person', function(newPerson, oldPerson){
    // Ignore Angular's initial broadcast
    if(!newPerson){
        return false;
    }
    CbgenRestangular.one(newPerson.cars_url).get().then(function(data){
        // Deal with cars data
    });
});