I'm trying to understand what's the best way to store (and update) data from the api and share that data between siblings components. This is what I tried.
Saving the observable
export class MyExampleService {
private data: Observable<any>;
constructor(private readonly http: HttpClient) { }
getData(): Observable<string[]> {
//if we already got the data, just return that
if (data) {
return data;
}
//if not, get the data
return this.http.get<string[]>('http://my-api.com/get-stuff')
.pipe(tap((returnedData: string[]) => {
//save the returned data so we can re-use it later without making more HTTP calls
this.data= returnedData;
}));
}
}
But this approach doesn't really fit my needs because it doesn't use any subject and I want to tell my other components when data changes.
Using subjects
export class MyExampleService {
private dataSbj: BehaviorSubject<any> = new BehaviorSubject(null);
readonly data$ = this.dataSbj.asObservable();
constructor(private readonly http: HttpClient) { }
getData(): Observable<string[]> {
if (dataSbj.getValue() === null) {
return this.http.get<string[]>('http://my-api.com/get-stuff')
.pipe(tap((returnedData: string[]) => {
//save the returned data so we can re-use it later without making more HTTP calls
this.dataSbj.next(returnedData);
}));
}
}
}
Then I would simply subscribe to the getData only the first time and subscribe to the data$ observable in all other components. (In this case I have one parent component and more child routes, so I would subscribe to getData() in the parent component and subscribe to the data$ in all child routes).
This last approach works but I'd rather use the same function to retrieve the same data and not by subscribing to different observables.
Is this considered a good approach or is there something better I could do instead?