Angular 8 中的 behaviorsubject 和 observable

behaviour subject and observable in Angular8

我收到了调用了 3 次的休息服务数据调用。我需要创建一个数据服务来减少一次调用,以便它保留本地 copy.if 副本尚未填充,它会点击 api 来获取它们。它应该只执行一次。因此,需要一个 bool 来指示 get 调用的状态。 如果尚未调用以获取数据,请切换 bool 并获取数据。 我知道这可以做到,如果 该组件将订阅可观察的,并且当数据服务有数据时,它将通过 BehaviorSubject 提供它。但不确定如何实现它,因为我还没有处理过可观察对象和行为主题。对此的任何指导表示赞赏。谢谢

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

我创建了如下数据服务:

  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);
    }
  }