I am studying angular now. When it comes to data sharing using service, many are recommending that we should use Subject like BehaviorSubject. But should we do it all the time?
@Injectable({
providedIn: 'root'
})
export class DataService {
private imageUrls = new Map<number, string>();
public imageUrlsSubject = new BehaviorSubject(this.imageUrls);
public size(): number {
return this.imageUrls.size;
}
public set(id: number, url: string): void {
this.imageUrls.set(id, url);
this.imageUrlsSubject.next(this.imageUrls);
}
public get(id: number): string {
return this.imageUrls.get(id);
}
public has(id: number): boolean {
return this.imageUrls.has(id);
}
}
I wrote a service like this following this practice. It makes me wonder: Do we really need Subject here? Can I just get rid of imageUrlsSubject under the context that another component just need to use the map in the DOM.
<img
*ngIf="dataService.has(row.id)"
[src]="dataService.get(row.id).url">
And in another component maybe I just need to call dogDataService.set to update the map.
this.dataService.set(id, url);
If I get rid of Subject, will it bring some potential drawbacks here?
Thanks!