There seem some similar questions and answers. However, none seems answering mine. I have a mat-table, in each row of it a change was triggered by selecting a option from a dropdown within a mat-cell. And thus I can console.log the data of this specific row with the change.
html:
<mat-row *matRowDef="let row; columns: columnsToDisplay;"
(click)="selectDataRow(row);"</mat-row>
service.ts:
private subsSource = new BehaviorSubject<ISubs>(null);
subs$ = this.subsSource.asObservable();
component.ts:
constructor(private subsService: SubsService) { }
selectDataRow(row) {
console.log(row);
//to store this row data to the subs$ defined in the service
this.subsService.subs$ = row;
}
As expected, the row data was indeed logged to the console.
Now, I want to consume the observable variable "subs$" in another component - ReviewComponent
export class ReviewComponent implements OnInit {
constructor(private subsService: SubsService) { }
ngOnInit(): void {
this.getSubs();
}
getSubs() {
this.subsService.subs$.subscribe(res => {
console.log(res);
});
}
Unfortunately, I got null log for the subs$ observable from the 2nd component.
Can anyone help point out what I did incorrectly and how to get it work?
ngOnDestroy()
, you destroy the subscribtions in order to prevent from memory leak. I suggest you to have a look at this issue if you useBehaviourSubject
Angular Best Practice: Unsubscribing (RxJS Observables). - Murat Yıldız