简体   繁体   中英

Wait for promise in RootCtrl Angular $http

I have a method in my RootCtrl that makes a call to my http api, and returns the result.

$scope.checkAccess = function(){
    var result = MyService.me();
    result.then(function(response){
        console.log(response);
        if (response.data != 'false'){
            return true;
        }
        else{
            return false;
        }
    });
}

But when I try to call this method in one of the child controllers, like so...

var access = $scope.checkAccess();

it tells me access is undefined.

What am I doing wrong here?

Here is what the Service call looks like.

me: function() {
    return $http({
        url: 'http://localhost:5000/api/me',
        method: 'GET'
      });
}

You forgot to actually return the promise object.

Here you go:

$scope.checkAccess = function(){
    var result = MyService.me();
    return result.then(function(response){
        console.log(response);
        if (response.data != 'false'){
            return true;
        }
        else{
            return false;
        }
    });
}

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