0

I am developing an app in M.E.A.N stack. I'm using an angular controller (from a directive), and a service. The controller calls the service, the service sends a GET request to NodeJS and gets a result. Then I log the result in the service and I get the data.

The problem is that the controller also logs the service before the controller gets results.

In services.js:

var self = this;
self.show = function() {
    $http.get('/contactlist').success(function(response) {
        console.log(response);
        return response;
    });

In directives.js:

this.contacts = contactsSrv.show();
console.log(this.contacts);

And that's what I see in the console: Image

(The directive logs before it gets results from contactsSrv.show())

How can I make the contactsSrv.show() asynchronous?

Thanks!

1

2 Answers 2

2

Using .then as promise return

service.js

var self = this;
self.show = function() {
    return $http.get('/contactlist');
};

directive.js

contactsSrv.show()
    .then(function (response) {
        console.log(response);
        this.contacts = response;
    });
Sign up to request clarification or add additional context in comments.

3 Comments

@KrzysztofSafjanowski sens of answer? I was changing this to work as it was the top voted answer.
@K.Burrell - to clarify - top voted answer was wrong, was not working in expected way and someone vote for it.
@KrzysztofSafjanowski Yes that is correct, I thought it would be easier for clarity to correct the top answer.
1

$http.get replaced by $http.jsonp as I need to retrive some data from ouside stackoverflow.

Replace success with then method - so you can chain results in controller / run section.

angular.module('app', [])
  .service('contactsSrv', function($http) {
    this.show = function() {
      return $http.jsonp('//public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK').then(function(response) {
        return response.data;
      });
    }
  }).run(function(contactsSrv) {
    contactsSrv.show().then(function(r) {
      console.log('found posts', r.found)
    })
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app'>
</div>

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.