I'm new to RXJS and would to know if what I am doing is best practice. I have an API whihc returns a list of countries. I need to use this list in several different components. I have an external api that returns this, it can be very slow.
I have a service to call this API. In the constructor of this service I kick off the HTTP request which then passes the list to a BehaviorSubject. I need to use the unedited list in one component this subscribes the BehaviorSubject. Another component will use selected values from the list and I am using the getCountryById function to do this and return a single value in a string
Should I be using AsyncSubject to do this and is it bad practice to use this.CountriesSubject.value in my getCountryById function, should I also be using a BehaviorSubject.subscribe in there as well?
All of this does need to happen in the service
Thanks for your time :-)
export class CountryListService implements OnDestroy {
private baseUrl = 'api/countries/';
private CountriesSubject = new BehaviorSubject<country[]>([]);
Countries$: Observable<Country[]> = this.CountriesSubject.asObservable();
constructor(private http: HttpClient) {
this.getCountries();
}
getCountries() {
console.log('=======fetching Countries from API');
this.http.get<any>(this.baseUrl + 'Countries').subscribe((data) => this.CountriesSubject.next(data?.countries));
}
getCountryById(id: any[]) {
if (!this.CountriesSubject.value) {
return undefined;
}
const country = this.CountriesSubject.value.find((f) => {
//Logic in here to get a country by and return its name
});
return country?.name;
}
ngOnDestroy() {
this.CountriesSubject.complete();
}
}