2

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. I can do this by nesting another $http.get with the first one, but this seems rather stupid. What is the best way to assign the id of the response, data.id, to a variable? 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
});

3 Answers 3

1

Why don't you watch your variable, in this case $scope.id like this:

$scope.$watch('id', function() {
       // Http request goes here
       $http.get(...)
});

When you assigned any value to $scope.id your "watch function" will be triggered.

Sign up to request clarification or add additional context in comments.

Comments

0

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:

startAJAX(thunk, bar, function(id) {
    $http(id).....

    });
});

Comments

0

Using a watch() method isn't necessary. 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.
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.