Sharjil Khan Sharjil Khan - 2 months ago 8
AngularJS Question

$http then method is not setting an array

I have create a service in service.js file in which I am using $http to get the list of posts. Here is the code of service.js.

app.service('PostService', function ($http, $log) {
var post =[];
var err = "";

$http({
method : 'GET',
url : 'http://myblog.local/wp-json/wp/v2/posts'
})
.then(function(response){
post = response.data;
}, function(reason){
err = reason.data.message;
});

this.getPost = function () {
return post;
};
this.getError = function () {
return err;
};});


And here it is my controller where I am using the service:

app.controller('BlogController', function($scope, $log, PostService){
$scope.postModel = PostService.getPost();
$scope.errorMessage = PostService.getError();
});


Everytime when I call getPost and getError method, it gives me nothing. Though $http is successfully getting response from the url. Why then method is not setting up the variable post and err.

Answer

You are using incorrect pattern of calling server. Http call is async action, so it takes some time to execute the code while running getPost() is a simple function which returns value just after you call it even if the value is still empty. So what you need to do here is to return Http call and assign it to needed model, just after it returns value.

app.service('PostService', function ($http, $log) {
var post =[];
var err = "";


this.getPost = function () {
   return $http({
        method : 'GET',
        url : 'http://myblog.local/wp-json/wp/v2/posts'
    })
    .then(function(response){
        return response.data;
    }, function(error){
        return error;
    });
};

});


app.controller('BlogController', function($scope, $log, PostService){
    PostService.getPost().then(function(post){
        // here you can put logic to check is post an data or error
        $scope.postModel = post;
    });
});
Comments