简体   繁体   English

从通用文件中调用angular Observable.subscribe()

[英]Calling angular Observable.subscribe() from common file

I am calling the below function from two file( ie x.ts and y.ts) but on checking from third party tool it showing me duplicate code in both file. 我从两个文件(即x.ts和y.ts)中调用以下函数,但是从第三方工具检查时,它显示了我在两个文件中都有重复的代码。 It is below message service which i am calling in both file. 我在两个文件中都在消息服务下面。

this.dataSubscription = this.dataService.allmesgeObeject.subscribe(data=> {
  if (data) {
    this.x= data.x;
    this.y= data.y;
  }
});

Can there be any way of putting subscribe function to a common file and received data it in their respective file. 可以采用任何方式将订阅功能置于通用文件中并将其接收到的数据存储在各自的文件中。

You can create Subject in your service and then subscribe to it from your two components. 您可以在服务中创建主题,然后从两个组件中进行订阅。 That way you will call the API only once and both components will be updated with the latest data 这样,您只需调用一次API,两个组件都将使用最新数据进行更新

    export class DataService{
      public allMessages: Subject<any> = new Subject();

      constructor(
        private http: HttpClient
      ) { }

      allmesgeObeject() {
        return this.http.get(...).pipe(
          map((result) => {
             this.allMessages.next(result);
          }));
      }
}

Then call it once from outside the service 然后从服务外部调用一次

this.dataService.allmesgeObeject.subscribe();

And now in two of your components you can subscribe to that subject you previously created. 现在,在您的两个组件中,您可以订阅先前创建的主题。

this.dataService.allMessages.subscribe(data=> {
  if (data) {
    this.x= data.x;
    this.y= data.y;
  }
});

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

相关问题 角度:Observable.subscribe取消同步怪异错误 - Angular: Observable.subscribe desync weird error Angular 2中的ChangeDetectionStrategy.OnPush和Observable.subscribe - ChangeDetectionStrategy.OnPush and Observable.subscribe in Angular 2 Observable.subscribe() 在 IE 中无法处理 Angular 7 中的组件更改 - Observable.subscribe() not working in IE on component change in Angular 7 将Observable.subscribe()返回的值赋给const - Assign value returned by Observable.subscribe() to a const RxJs:如何关闭嵌套 observable.subscribe 调用的订阅 - RxJs : How to close subscription of nested observable.subscribe call 淘汰:上下文在observable.subscribe中的指令之前更改 - Knockout : context changed before the instruction in observable.subscribe 订阅Angular2中的Observable - Subscribe to Observable in Angular2 Angular 组件中基于不同数据的组件之间单次/多次公共 Observable 订阅的最佳方法 - Best Approach for single/multiple time common Observable subscribe between components based on different data stream in Angular component 角度如何从可观察订阅的结果中设置组件变量 - angular how to set a component variable from result in observable subscribe 内部订阅并在Angular中返回可观察的对象 - Subscribe inside subscribe and return an observable in Angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM