0

Hi I am having difficulty with having a function inside a controller in angular return a value to a variable.

Here is the function:

var getUser = function(user_id, key) { 
    var user;

    var request = {
        method: 'GET',
        url: 'http://localhost/torteez/api/user/' + user_id,
        headers: {
            'Content-Type': 'application/json'
        }
    };

    $http(request)
        .then(function successCallback(response) {
            if(key === 'all') {
                user = response;
            } else {
                user = response.data[0][key];
            }
        }, function errorCallback(err) {
            console.log(err);
        });

    return user;
};

And here is the variable where the user detail should be returned to:

var username = getUser(row['user_id'], 'username');

Please, tell where the problem is.

  • `$(http)` is asynchronous. – JLRishe Jul 12 '16 at 10:46
  • You need to look up a tutorial or sample, $http is async and doesn't return until the async call completes, so user will not be anything. You need to set something inside your callback to use it. – Jason Goemaat Jul 12 '16 at 10:46
  • The request is made async, so you will have to add a callback to your function... – Dennis Weidmann Jul 12 '16 at 10:46
  • getUser method makes an asynchronous request but it will return the variable user before the REST api call is complete. – Siva Jul 12 '16 at 10:47
  • I worked around a solution by creating a global variable $scope.firstname = '': and assigning it the value inside the function – user3237309 Jul 12 '16 at 11:53

0 Answers0