I have created an Angular service using npm generate service. This way, the service that is created, will be a singleton, i.e. the service can be used across the entire app. The service basically looks like this:
@Injectable({
providedIn: 'root'
})
export class SelectRowIdService {
private selectedRowIdState = new Subject<number>();
selectedRowId$ = this.selectedRowIdState.asObservable();
updateSelectedRowId(id: number) {
console.log('updateSelectedRowId(): ' + id);
this.selectedRowIdState.next(id);
}
}
Now consider a table: Every time I click on a row, I am executing a method onRowClick(), which is calling updateSelectedRowId(). This method gets called with the correct id every time I click on a row, I verified this. The service's updateSelectedRowId() is called as well.
Inside another component, not the table, I am injecting the SelectRowIdService and subscribe to selectedRowId$:
private selectedRowId?: number;
constructor(private selectRowIdService: SelectRowIdService) {}
ngOnInit() {
this.selectRowIdService.selectedRowId$.subscribe((id: number) => {
this.selectedRowId = id;
console.log('DemoComponent: ' + this.selectedRowId);
});
}
Now, this subscription is never executed and I just cannot understand why. Since I have verified that the service's updateSelectedRowId() method is called when clicking on a table row, I would have figured that the above mentioned subscription would be executed. I can only assume that this has something to do with the way I registered the service, that's why I mentioned this at the beginning of this post. Does someone have an idea about this?