0

I am new to angular, in an application I am writing angular services for doing REST API call.

What I am doing like below:

    App.service('dataService', function(){
    this.getNewsAndTweets = function(){
        var newsCall = $http({
            method: 'GET',
            url: '/api/news/'
        });

        var tweetsCall = $http({
            method: 'GET',
            url: '/api/tweets/'
        });
        $q.all(newsCall, tweetsCall).then(function(values) {
            var news = values[0].data.results;
            var tweets = values[1].data.results;
            var a = doSomeThing(news);
            var b = doSomeThingToo(tweets);
            return [a, b];  
            });

        }
}

As $q.all(newsCall, tweetsCall).then is an asynchronous call, I am getting null array in news when I am calling my service.

Inside my controller I am calling it like dataService.getNewsAndTweets() and getting null array, as far as my understanding as $q is an async call which is returning data later.

How can I resolve this issue?

Thanks in advance.

1 Answer 1

1

you have to return the promise in your service

return $q.all(newsCall, tweetsCall).then(function(values) {
        var news = values[0].data.results;
        var tweets = values[1].data.results;
        var a = doSomeThing(news);
        var b = doSomeThingToo(tweets);
        return [a, b];  
        });

en then in your controller wait for it to resolve:

dataService.getNewsAndTweets().then(function(data){
    $scope.news = data[0];
    $scope.tweets = data[0];
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.