[英]Make a second get request in AngularJS
The following code works, and I get the JSON below returned. 以下代码有效,我在下面返回了JSON。 What I'm interested in is the
cars_url
. 我感兴趣的是
cars_url
。 How can I get the URL (and what is the best way) then make a secondary get request? 如何获取URL (以及最佳方式)然后进行二次获取请求?
JSON 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 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)
}
);
}
]);
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
});
}
);
}]);
Nesting the requests can get messy if you have more than one level deep. 如果您有多个级别,嵌套请求可能会变得混乱。 In that case, you should use $q to control the flow of the requests.
在这种情况下,您应该使用$ 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
});
});
}]);
If you want to do it any time $scope.person
changes (which happens in the response from the person
request), you could set up a $watch
in your controller. 如果你想在任何时候
$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
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.