繁体   English   中英

如何将响应从服务传递到控制器Angularjs?

[英]how to pass a response from the service to the controller Angularjs?

我在服务中有一个要求:

getCommentText(id: number) {
    var data = null
    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);
    }

我需要将响应从服务传递回控制器。 最终将得到什么: var text =(响应)我试图在控制器中使用订阅。 但这对我不起作用。 这是第一位Angulyar,我不太了解他。 我该怎么办?

您的服务应返回承诺:

 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返回一个Promise Promise是一个表示值或错误的对象,两者都会在将来的某个时刻发生。 由于这是一个对象,因此可以将其返回,如下所示:

getCommentText(id: number) {
  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((text) => {
      this.commentText = text
    })

由于getCommentText可能会失败,因此您应该小心处理失败情况。 另外,由于这是异步的,因此请考虑向用户显示某种加载指示符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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