简体   繁体   中英

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?

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); }); } 

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM