I am currently using Angular 10 and have developed a server that returns an observable:
export class CountrySelectionService {
private _activeCountry = new BehaviorSubject(this.getCountries()[0]);
public getActiveCountryPush(): Observable<CountrySpec> {
return this._activeCountry.asObservable();
}
constructor(private utilService:UtilService){}
getCountries(): CountrySpec[] {
return [new CountrySpec("assets/images/canadaFlag.svg", Country.CA, "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84f7e5e8e1f7c4e0f3edeae2ebaae7ebe9">[email protected]</a>"),
new CountrySpec("assets/images/usaFlag.svg", Country.US, "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2251434e47516246554b4c444d0c414d4f">[email protected]</a>")]
}
setActiveCountry(countrySpec: CountrySpec): void {
this._activeCountry.next(countrySpec);
}
}
Within the app.component.ts(root component) file, in the ngOnInit function, I call the above method:
ngOnInit(): void {
this.countrySelectionService.getActiveCountryPush().subscribe({
x=> { someFoo(x.name) }
});
}
I was expecting the someFoo callback method to only be triggered when the _activeCountry property is updated. However, it seems that the someFoo callback method is being called not only when _activeCountry is updated but also when navigating to another page within the app.
Any suggestions on why the someFoo method is being triggered even when _activeCountry is not updated? And how can I resolve this issue?