Simplified use case:
- I have Angular app with multiple modules, most (not all) of the modules use a list of airports
- I want to create a
global-cache.service.ts
and cache the airport list inBehaviorSubject
which will be exposed as Observable. I only want to initialize theBehaviorSubject
(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