I try to take data from observables to component.
I can not get the data into the array in the typescript, I still get the Observable object and the message of type negatives. However, in HTML the loop correctly prints the data that came.
Services :
@Injectable()
export class DataService {
private _dataListSource: BehaviorSubject<Data[]> = new BehaviorSubject<Data[]>([]);
constructor(private http: HttpClient) {
}
getDataList(): Observable<any> {
return this.http.get<Data[]>('/rest/data/lastDatas').map(res => {
this._dataListSource.next(res);
console.log(res);
});
}
subscribeToDatas(): Observable<Data[]> {
return this._dataListSource.asObservable().distinctUntilChanged();
}
getData(): Observable<Data[]> {
return this.http.get<Data[]>('/rest/data/lastDatas');
}
}
TypeScript class:
export class DataComponent implements OnInit {
dataStatuses: Data[];
public dataList$: Observable<Data[]>;
constructor(public dataService: DataService) {
}
ngOnInit() {
this.dataList$ = this.dataService.subscribeToDatas();
this.dataService.getDataList().subscribe();
console.log("Informacja ", this.dataList$);
}
}
HTML :
<div *ngIf="dataList$ | async; let dataList; ">
<div *ngFor="let data of dataList">
{{data.id}}
</div>
</div>