Дмитрий
Дмитрий

Reputation: 1109

how to pass a response from the service to the controller Angularjs?

I have a request in the service:

getCommentText(id: number) {
    var data = null
    this.$http.post(this.path + '/' + id + '/GetComment', data, {
        headers: { "Content-Type": "application/json" }
    }).then(r => r.data);
}

and controller

    openComment($event) {
        this.commentid = $event.target.id;
        this.service.getCommentText(this.commentid);
    }

I need to transfer the response from the service back to the controller. What would eventually have: var text = (response) I tried to use subscribe in the controller. But it does not work for me. This is the first Angulyar and I do not know him very well. How should I do it?

Upvotes: 1

Views: 59

Answers (2)

Dan
Dan

Reputation: 10538

$http.post returns a Promise. A Promise is an object which represents either a value or an error, both of which will occur at some point in the future. Since this is an object, it can be returned, like so:

getCommentText(id: number) {
  return this.$http.post(this.path + '/' + id + '/GetComment', data, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(r => r.data);
}

This can then be consumed within your controller:

openComment($event) {
  this.commentid = $event.target.id
  this.service.getCommentText(this.commentid)
    .then((text) => {
      this.commentText = text
    })

Since getCommentText could fail, you should take care to also handle the failure case. Additionally, since this is asynchronous, consider displaying some kind of loading indicator to the user.

Upvotes: 0

Faly
Faly

Reputation: 13346

Your service should returns the promise:

getCommentText(id: number) {
    var data = null
    return this.$http.post(this.path + '/' + id + '/GetComment', data, {
        headers: { "Content-Type": "application/json" }
    }).then(r => r.data);
}

openComment($event) {
    this.commentid = $event.target.id;
    this.service.getCommentText(this.commentid).then(response => {
        console.log(response);
    });
 }

Upvotes: 2

Related Questions