[英]nested angular http.get calls
I have a simple angular $http.get, which returns a json object, but I want the id from the json to do another $http.get. 我有一个简单的有角$ http.get,它返回一个json对象,但是我希望json中的id可以执行另一个$ http.get。 I can do this by nesting another $http.get with the first one, but this seems rather stupid. 我可以通过在第一个$ http.get中嵌套另一个来实现此目的,但这似乎很愚蠢。 What is the best way to assign the id of the response, data.id, to a variable? 将响应的ID data.id分配给变量的最佳方法是什么? I'm having some issues with variable scope; 我在可变范围方面遇到了一些问题; trying to simply assign the value to a variable. 尝试简单地将值分配给变量。
$http.get('/api/v1/foo/userinfo?thunk='+thunk+'&bar='+bar).success(function(data) {
$scope.id = data.id
}).then(function(data){
$scope.id = data.data.id
});
Why don't you watch your variable, in this case $scope.id like this: 您为什么不看您的变量,在这种情况下,像这样的$ scope.id:
$scope.$watch('id', function() {
// Http request goes here
$http.get(...)
});
When you assigned any value to $scope.id your "watch function" will be triggered. 当您为$ scope.id分配任何值时,将触发“监视功能”。
Can use callbacks to make it cleaner. 可以使用回调使它更整洁。 Wrap your call in a function: 将您的呼叫包装在一个函数中:
function startAJAX(thunk, bar, callback) {
$http.get('/api/v1/foo/userinfo?thunk='+thunk+'&bar='+bar).success(function(data) {
callback(data.id);
});
}
Then make the call and do your next http call: 然后拨打电话并进行下一个http通话:
startAJAX(thunk, bar, function(id) {
$http(id).....
});
});
Using a watch() method isn't necessary. 不需要使用watch()方法。 Use callbacks, or if you want to be fancy use promises to keep things organized. 使用回调,或者如果您想花哨的话,请使用诺言使事情井井有条。
var callOnePromise = $http.get('/api/foo');
var callTwoPromise;
callOnePromise.success(function(data) {
callTwoPromise = $http.get('/api/bar/' + data.id);
});
callTwoPromise.success(function() {
//Cool stuff here.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.