简体   繁体   中英

returning value to higher scope inside from a chained functions in angular js

I have a function getUsers that I want to return JSON from an web api .. but I cant seem to get the data out, I can't return the data because the function is inside $http. What should i do ?

function getUsers() {
            $http({ method: 'GET', url: '/api/loginapi/userdetails' })
                     .success(function (data, status, headers, config) {
                         details = data;
                     });
            return details;
           }

$http makes an asynchronous call, so you can't immediately return fetched data.

What you can return is a promise . Good news, $http() returns one:

function getUsers() {
    return $http({ method: 'GET', url: '/api/loginapi/userdetails' });
}

Then you can use your function:

getUsers().then(function(data) {
    var details = data;

    // Process your details!
});

You can access data there for sure, nothing is 'inside' $http , I suggest you pass in a callback to getUsers() and do whatever you want with the returned data:

var getUsers=function(callback){
            $http({ method: 'GET', url: '/api/loginapi/userdetails' })
                     .success(function (data, status, headers, config) {
                         callback(data);
                     });
}

and use it like this inside your controller:

getUsers(function(users){
    $scope.whatever = users;
})

I created plunkr for your question http://plnkr.co/edit/lqX4apmvnKM3i5jGZDQM?p=preview

$http return a promise. Please read details about promise at http://johnmunsch.com/2013/07/17/angularjs-services-and-promises/ . It is an important understanding if you want to write asynchronous application. This is another useful link - Inside my own Angular service, how do you get the return value back to the Controller that called the service? . Refer to answer. It explains how to use promise and deffered in angularjs.

    var app = angular.module('plunker', []);


    app.service('UserService', ['$http', '$q',
        function($http, $q) {
            this.getUser = function() {
                return $http({
                    method: 'GET',
                    url: 'data.json'
                });
            };
        }
    ]);
    app.controller('MainCtrl', function($scope, UserService) {
        $scope.user = {};
        UserService.getUser().then(function(response){
            $scope.user = response.data;
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM