Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create behavior subject for object and subscribe to it on another component?

I created a behaviour subject in a service class.

public personObject: BehaviorSubject<any> =
    new BehaviorSubject<any>({ personId: 1, name: 'john doe' });

On a component that imports this service, i subscribed this behaviour subject like this:

this._subscription.add(
    this._bankService.personObject.subscribe(data => {
        this.personObject = data;
        console.log(data);
    })
);

But I am not able to get exact dataset in the behaviour subject.

Edit I forgot to mention that I used ViewContainerRef to create my sibling component which I added to an answer with a few comments.

like image 953
Prabesh Avatar asked Oct 12 '17 09:10

Prabesh


2 Answers

Service

@Injectable()
export class DataService {

  private _dataListSource: BehaviorSubject<IData[]> = new BehaviorSubject([]);
  dataList: Observable<IData[]> = this._dataListSource.asObservable().distinctUntilChanged();

  getDataList(): Observable<any> {
      return this.httpService.get('/data').map(res => {
          this._dataListSource.next(res);
      });
  }
}

TS file

export class DataComponent implements OnInit {

    public dataList$: Observable<IData[]>;

    constructor(public dataService: DataService) {}

    ngOnInit() {
        this.dataList$ = this.dataService.dataList;
        this.dataService.getDataList().subscribe();
    }
}

HTML file

<div *ngIf="dataList$ | async; let dataList; ">
    <div *ngFor="let data of dataList">
        {{ data | json}}
    </div>
</div>
like image 56
Dmitry Grinko Avatar answered Sep 23 '22 23:09

Dmitry Grinko


I forgot to mention that I was using I was using ViewContainerRef to create a sibling component and it turns out behavior subject does not work the same way with component created using ViewContainerRef.

Other wise Behaviour subjects of any object work exactly like with number or string. I used @Input to send data to component for now.

like image 35
Prabesh Avatar answered Sep 22 '22 23:09

Prabesh