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

扶醉桌前 提交于 2019-11-29 22:35:32

问题


I have 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 have subscribed this behavior 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 data set in behavior subject. Please help.

Edit I forgot to mention that i have used ViewContainerRef to create my sibling comnponent. So i have added a answer with few comments on my issue.


回答1:


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);
      });
  }

and then you can use it in your component

export class DataComponent implements OnInit {

    public dataList$: Observable<IData[]>;

    constructor(public dataService: DataService) {}

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

and your html

    <div *ngIf="dataList$ | async; let dataList; ">
        <div *ngFor="let data of dataList">
            {{ data | json}}
        </div>
    </div>



回答2:


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.



来源:https://stackoverflow.com/questions/46706497/how-to-create-behavior-subject-for-object-and-subscribe-to-it-on-another-compone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!