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

时间:2017-10-12 09:49:40

标签: angular typescript object rxjs behaviorsubject

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.

2 个答案:

答案 0 :(得分:5)

服务

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

然后您可以在组件中使用它

export class DataComponent implements OnInit {

    public dataList$: Observable<IData[]>;

    constructor(public dataService: DataService) {}

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

和你的HTML

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

答案 1 :(得分:0)

我忘了提到我正在使用我正在使用ViewContainerRef创建一个兄弟组件,事实证明,行为主题与使用ViewContainerRef创建的组件的工作方式不同。

其他明智的任何对象的行为主题与数字或字符串完全相同。我现在使用@Input将数据发送到组件。