2

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>
2
  • what are you getting in console.log(); ?? Commented Feb 1, 2018 at 9:46
  • Informacja Observable {_isScalar: false, source: Observable, operator: DistinctUntilChangedOperator} Commented Feb 1, 2018 at 10:19

1 Answer 1

3

Your dataList$ returns an Observable, that is correct. The html still works because you are using an async pipe, which automatically does the "subscribe" part for you in HTML.

If you want to see what does dataList$ return, simply subscribe to it:

this.dataList$.subscribe(data=>{
    console.log("data from dataList! ",data);
})
Sign up to request clarification or add additional context in comments.

2 Comments

its working thanks! I try to put object lamp to my dataObjects array. And its not working. i try do this by dataObjects.push(data)
Just a reminder to accept answers that solved your question!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.