-1

Simplified use case:

  1. I have Angular app with multiple modules, most (not all) of the modules use a list of airports
  2. I want to create a global-cache.service.ts and cache the airport list in BehaviorSubject which will be exposed as Observable. I only want to initialize the BehaviorSubject (hit the DB) when user lands on component that subscribes to that Observable (vs initializing it in the service controller)

Here's the starting point, can't get it to work (see comment after this.getAirpotsFromDB() call) :

global-cache.service.ts

airports: BehaviorSubject<string[]> = new BehaviorSubject(null);
get airports$(): Observable<string[]> {
  if (this.airports.getValue() == null) {
    //get list from db, and initialize the subject
    this.getAirportsFromDB();
    //**PROBLEM:** how do I return `this.airports.asObservable()` after it's initialized with data from the call above or return it from inside the call?
  }
  else{
    //list initialized, emit from subject (don't hit db)
    return this.airports.asObservable();
  }
}

getAirportsFromDB() {
  this.http.get<string[]>('/api/airports').subscribe((_result) => {
    this.airports.next(_result);
  });
}

myComponent1.ts

//imports global-cache.service but never subscribes to airports$ (service has many other arrays that are used here)
//User lands here first, `getAirportsFromDB()` never gets called, user goes to myComponent2

myComponent2.ts

...
airports$: any = this.globalCacheService.airports$;
//subscribed in html `airports$ | async`
...
//user lands here, `getAirportsFromDB()` is called, `airports` BehaviorSubject is initialized
//user then goes to myComponent3

myComponent3.ts

...
airports$: any = this.globalCacheService.airports$;
//subscribed in html `airports$ | async`
...
//`airports` BehaviorSubject emits last value (initialized in Component2). `getAirportsFromDB()` does not get called again

roman m
  • 26,012
  • 31
  • 101
  • 133

3 Answers3

2

You can try something like below, just use tap operator and save the value of http request in the BehaviorSubject and return Observable from getAirportsFromDB

export class Service {

  airports: BehaviorSubject<string[]> = new BehaviorSubject(null);

  get airports$(): Observable<string[]> {
    return this.airports.getValue()
        ? this.airports.asObservable()
        : this.getAirportsFromDB();
  }

  getAirportsFromDB(): Observable<string[]> {
    return this.http.get<string[]>('/api/airports')
      .pipe(
        tap((_result) => this.airports.next(_result))
      )
  }
}

Minor update: The BehaviorSubject observable isn't getting returned on the first call so subsequent calls to the getter wouldn't update the view, so you can use the code above only in case, that you use it as the cache and don't want to receive any updates

Slawa Eremin
  • 5,264
  • 18
  • 28
  • The BehaviorSubject observable isn't getting returned on the first call so subsequent calls to the getter wouldn't update the view – Drenai Mar 17 '22 at 08:31
  • it shouldn't, I returned the value from http request and just additionaly cache it through tap – Slawa Eremin Mar 17 '22 at 08:33
  • yes, there is the name of service `global-cache.service` so it's just a dictionary, it should not receive any updates – Slawa Eremin Mar 17 '22 at 08:39
  • @SlawaEremin I need to return the BehaviorSubject from the first call, there's a lot more going on in myComponent2 that I've omitted to keep things simple – roman m Mar 17 '22 at 18:42
1

Ended up going with shareReplay(1); way easier and does exactly what I wanted

global-cache.service.ts

airports$: Observable<string[]> = this.getAirportsFromDB();

getAirportsFromDB() {
  return this.http.get<string[]>('/api/airports').pipe(shareReplay(1));
}
roman m
  • 26,012
  • 31
  • 101
  • 133
-2

In get airports() you should always return the observable. If the DB API hasn't already been called then call getAirportsFromDB as you are currently doing

It's up to the components that subscribe to the returned observable to check the returned data and update their views based on this (that will be asynchronous)

Angular University site has some detailed examples of services that would also help

Drenai
  • 11,315
  • 9
  • 48
  • 82