Reputation: 1149
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?
Upvotes: 5
Views: 2695
Reputation: 826
If your second component appears elsewhere and after navigating away from your table, then this is the expected behavior. Basically, with Subject
s, if you come late to the party, you won't get anything. Put in programming words, if you subscribe after the values have been emitted, then you won't receive any value.
In that case, you should use a BehaviorSubect
instead.
Here is a StackBlitz link that demonstrates both cases.
You may also find helpful this article on component communication.
Upvotes: 4