简体   繁体   English

Angular8 中的行为主体和可观察对象

[英]behaviour subject and observable in Angular8

I have get rest service data call that is called 3 times.我收到了 3 次调用的 rest 服务数据调用。 I need to create a data service to reduce the call to once so it keeps a local copy.if the copy hasn't been populated yet, it hits the api to get them.我需要创建一个数据服务来减少一次调用,以便它保留一个本地副本。如果尚未填充副本,它会点击 api 来获取它们。 it should do this only once.它应该只执行一次。 So, need a bool that indicates the status of the get call.因此,需要一个指示 get 调用状态的布尔值。 If not already making a call to get data, toggle the bool and get the data.如果尚未调用获取数据,请切换布尔值并获取数据。 I know this can be done if The component would subscribe to observable, and when the data service had data, it would provide it via the BehaviorSubject.我知道如果组件订阅 observable 可以做到这一点,并且当数据服务有数据时,它将通过 BehaviorSubject 提供它。 BUt not sure how to implement it because i havent worked with observables and behaviour subject.但是不确定如何实现它,因为我没有使用可观察对象和行为主题。 Any guidance on this is appreciated.对此的任何指导表示赞赏。 Thanks.谢谢。

Here is my sample stackblitz https://stackblitz.com/edit/angular-sqxp9e?file=src%2Fapp%2Fnotifications-data.service.ts这是我的示例 stackblitz https://stackblitz.com/edit/angular-sqxp9e?file=src%2Fapp%2Fnotifications-data.service.ts

I created the data service as below:我创建了如下数据服务:

  private notificationsSubject = new BehaviorSubject<any>([]);
  private loaded = false;

  public notifications$ = this.notificationsSubject.asObservable();
  public data = [];


  constructor(private restSvc: RestService) { }

  getNotification$(): void {

    if (!this.loaded) {
      this.loaded = true;
      this.restSvc.getData("/api/app/getnotifs").subscribe((data: any) => {
        this.data = data;
        this.notificationsSubject.next(this.data);

      });
    }
    else {
      this.notificationsSubject.next(this.data);
    }
  }

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

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