I have a service in my Angular application that fetches specific data. For this reason, this service offers a method called getData():Observable<Data>
.
However, it should also contain two or three other methods that provide subsets or filtered data.
It seems strange to me to call getData()
multiple times just to pass the result to getFilteredData(data$)
.
But it also doesn't seem right to me to let the getFilteredData()
call the getData()
method independently, since these would be redundant queries.
How can I remember the result of getData()
(considering the Angular style guide)?
export class DataService {
getData():Observable<Data> {
//...
}
getFilteredData():Observable<Data> {
return this.getData().pipe( //<--- redundant call of getData() since Ive already used getData() at this point in my app
//...
);
}
}
You asked the right qeustion. I suggest you to make a new property with a BehaviorSubject
type as your state trigger. And another one to share the data - this allows you reuse the state value when it needs. Your code should look like this:
export class DataService {
readonly data$: Observable<Data>;
private readonly getNewData = new BehaviorSubject<Params>({});
constructor(private httpClient: HttpClient) {
this.data$ = this.getNewData.pipe(
switchMap(params => this.client.get(..., params)),
shareReplay(1),
);
}
getData(params: Params):Observable<Data> {
this.getNewData.next(params);
return this.data$.pipe(first());
}
getFilteredData():Observable<Data> {
return this.data$.pipe(
//...
);
}
}
You can use data$
directly to get data, or just use return value from getData
method.