Our root-based service offers the following features:
- Retrieves data once from an API
- Handles data mapping
- Shares data with other components when necessary
This data remains static throughout the app's lifecycle and only refreshes when the user reloads the browser. Since all data will be utilized, making HTTP requests for each getOneById()
call is inefficient. A filter performs faster in this scenario.
The structure of the service resembles this:
export class MyTypeService {
items: MyType[] = [];
items$ = new BehaviorSubject<MyType[]>(this.items);
constructor(private http: HttpClient) { }
getData(): Subscription {
return this.http.get<SearchResult>(
'path'
).pipe(
map((response: any) => {
this.items = response;
return this.items;
}),
catchError(error => {
// omitted for simplicity
this.handleError(error);
return of([]);
})
).subscribe(result => this.items$.next(result));
}
getOneById(id: string): MyType|null {
for (let item of this.items) {
if (item.id === id) {
return item;
}
}
return null;
}
}
Now facing these questions:
- Should the service itself subscribe to
items$
?
Or should all member functions likegetOneById()
subscribe?
(Which might mean thatitems
can be removed) - Is it best to invoke
getData()
in the constructor since values are crucial during runtime?
Or wait until the values are actually required? - How do I notify a component that it's safe to use
getOneById()
?