user10863293
user10863293

Reputation: 876

Why the value of my service is undefined when it's called out of $http

This is my service

app.factory('checkMembership', function ($http) {
    var membership;
    return {
        setIsMembership: function () {
            $http.get('api/User/checkMembership').then(function (response) {
                membership = response.data
            });
        },
        getIsMembership: function () {
            return membership
        }
    }
})

This is my controller

app.controller('appCtrl', function ($scope, $http, checkMembership) {
    checkMembership.setIsMembership()
    $scope.membership = checkMembership.getIsMembership()
    console.log($scope.membership)
})

When i check with console it says that membership is undefined, but it should be defined. But when I do this

app.controller('appCtrl', function ($scope, $http, checkMembership) {
    $http.get("api/anyAPIURL").then(function (response) {
        checkMembership.setIsMembership()
        $scope.membership = checkMembership.getIsMembership()
       console.log($scope.membership)
    })
})

I have my boolean in my console. So why out of an $http when i call my service it returns me undefined. How can I resolve this and still work with a service ?

EDIT : I had this

app.config(function ($httpProvider) {
    $httpProvider.useApplyAsync(true);
});

But I still have the same issue.

Upvotes: 0

Views: 39

Answers (0)

Related Questions