How to create behavior subject for object and subscribe to it on another component?
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>