【问题标题】:Calling angular Observable.subscribe() from common file从公共文件中调用 angular Observable.subscribe()
【发布时间】:2019-07-29 15:23:58
【问题描述】:

我正在从两个文件(即 x.ts 和 y.ts)调用以下函数,但是在从第三方工具检查时,它显示了两个文件中的重复代码。它位于我在两个文件中调用的消息服务之下。

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

有没有办法将订阅功能放到一个公共文件中,并在各自的文件中接收数据。

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您可以在您的服务中创建主题,然后从您的两个组件中订阅它。这样,您只需调用一次 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);
              }));
          }
    }
    

    然后从服务外部调用一次

    this.dataService.allmesgeObeject.subscribe();
    

    现在在您的两个组件中,您可以订阅您之前创建的主题。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-25
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 2023-04-05
      相关资源
      最近更新 更多