如何为对象创建行为主题并在另一个组件上订阅它?

如何为对象创建行为主题并在另一个组件上订阅它?

问题描述:

我在服务类中创建了一个行为主题。如何为对象创建行为主题并在另一个组件上订阅它?

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

在一个导入这项服务的组成部分,我已经订阅此行为主体是这样的:

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

但我不能够得到确切的数据在行为主体设定。请帮忙。

编辑 我忘了提及我已经使用ViewContainerRef来创建我的兄弟姐妹组件。所以我在我的问题上添加了一些没有评论的答案。

+0

你可以做一个演示? – martin

+0

添加有关服务和组件类的更多信息(代码) –

+0

为了简单起见,我只想使用BehaviorSubject在兄弟组件之间传递对象。只要提供有关如何执行操作的任何演示或文章都将有所帮助。谢谢 – Prabesh

我忘了提,我用我所用ViewContainerRef创建一个兄弟组件,事实证明,行为主体不能以组件创建的usi同样的方式工作ng ViewContainerRef。

其他智慧任何对象的行为主题都完全像数字或字符串一样工作。现在我使用@Input将数据发送到组件。

服务

@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>