简体   繁体   中英

behaviour subject and observable in Angular8

I have get rest service data call that is called 3 times. 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. it should do this only once. So, need a bool that indicates the status of the get call. 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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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