我在服务类中创建了一个行为主题。
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 创建了我的兄弟组件,我将其添加到带有一些评论的答案中。
最佳答案
服务
@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 文件
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>
关于angular - 如何为对象创建行为主题并在另一个组件上订阅它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46706497/