canbrian
canbrian

Reputation: 129

Pass observable from one component to another via service

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?

Upvotes: 0

Views: 1336

Answers (2)

Miri Gold
Miri Gold

Reputation: 390

Instead of initializing your observable, You need to use your subject:

component.ts:

selectDataRow(row) {
    this.subsService.setSubsSource(row);
}

service.ts:

setSubsSource(row){
    this.subsSource.next(row);
}

Everything else, just like you wrote

Upvotes: 0

Murat Yıldız
Murat Yıldız

Reputation: 12022

Try this:

private subsSource = new BehaviorSubject<ISubs>(undefined);

getSubsSource(): BehaviorSubject<ISubs> {
    return this.subsSource;
}

setSubsSource(param: any) {
    this.subsSource.next(param);
}

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.setSubsSource(row);
}

export class ReviewComponent implements OnInit {

    private subscriptions = new Subscription();

    constructor(private subsService: SubsService) { }

    ngOnInit(): void {  
        this.getSubs();  
    }

    getSubs() {
        this.subscriptions.add(this.subsService.subs$.subscribe(res => {
            if (res !== undefined) {
                console.log(res);
            }
        });
    }

    ngOnDestroy() {
      subs.forEach(sub => sub.unsubscribe());
    }
}

Hope this helps.

Upvotes: 1

Related Questions