angular 服务功能完成时通知组件 [英] Notify component when service function is complete in angular

查看:22
本文介绍了angular 服务功能完成时通知组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个对后端执行 http 查询的服务:

I writing a service which do a http query to the backend:

getPlacesForUser(){
 this.http.get("http://localhost:8080/processPlaces")
  .map(res => res.text())
  .subscribe(
    data => this.result = data,
    err => this.logError(err),
    () => console.log('Places Request completed')
  )
}

现在我想更新组件端,如果请求完成:

Now I want to update the components-side, if the request is completed:

processPlaces(){
 this._backendService.getPlacesForUser();
}

如何在组件和服务之间进行通信?

How can I communicate between the component and service?

此外,我还在寻找最佳实践.

Furthermore I searching for the best practice.

推荐答案

实际上,您可以直接从 getPlacesForUser 方法返回 observble 并在其上附加 subscribe 方法.

In fact, you can return the observble directly from the getPlacesForUser method and attach a subscribe method on it.

  • 服务

getPlacesForUser(){
  return this.http.get("http://localhost:8080/processPlaces")
    .map(res => res.text());
}

  • 组件

    processPlaces(){
     this._backendService.getPlacesForUser()
      .subscribe(
        data => this.result = data,
        err => this.logError(err),
        () => console.log('Places Request completed')
      );
    }
    

  • result 属性对应于您可以在组件中使用的组件的属性.

    The result attribute corresponds to an attribute of the component you can use in the component.

    您可以注意到 async 管道可用于直接利用表达式中的 observable(例如在 ngFor 中).

    You can notice that a async pipe is available to directly leverage observable in expressions (for example within an ngFor one).

    我认为这个答案可以帮助您:如何在 angular 2 beta 的服务中有效地使用 Http 组件?.

    I think that this answer could help you: How to Consume Http Component efficiently in a service in angular 2 beta?.

    希望对你有帮助蒂埃里

    这篇关于angular 服务功能完成时通知组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆