Please see How I Learned To Stop Worrying About Lifecycle Events. In your case, you’ve already done much of the work, because TemperatureService
is already present and available to provide Observable
s. I’m not sure from what you’ve posted whether currentPlace
is something that can or should also be tracked in the service, but assuming it isn’t:
type TemperatureScale = "c" | "f";
private scale$ = new BehaviorSubject<TemperatureScale>();
private scalify(temp: number, scale: TemperatureScale): string {
/* TODO */
}
displayTemperature(place: Place): Observable<string> {
return this.scale$.pipe(
map(scale => this.scalify(place.currTemp, scale));
}
Naturally, if there is a logical way to encapsulate the concept of “current place” into the service, then displayTemperature
can do all its work with no arguments, and the component no longer needs to track currentPlace
at all.