Consider:
this.getList().subscribe((data) => {
console.log("data", data);
this.listItems = data;});
Above is the method I am returning the observables from.
Consider:
this.getList().subscribe((data) => {
console.log("data", data);
this.listItems = data;});
Above is the method I am returning the observables from.
Try this, assign the observable to a component property
listItems$ = this.getList();
and then subscribe to the observable in the template with the async pipe.
<ng-container *ngIf="listItems$ | async as listItems">
{{ listItems | json }}
</ng-container>
No need for managing subscriptions.
the above method should work. I would suggest logging this.listItems after it is assigned to double check if you are unsure.
The problem you might be having is the order in which this runs. Remember, this happens asynchronously, so listItems is getting assigned after all the other normal component things happen.
A solution I often use (assuming your template references the data) is to hold the entirety of the template (or the area that uses the data anyways) in an ngIf :
*ngIf="this.listItems"
That way the template only shows after the subscription is complete.
Recommended way is not to subscribe inside component class (.ts
), rather use an observable.
listItems$ = this.getList(); // I agree with Adrian Brand
template: (assume you using table)
<table>
<tr *ngFor="let item of listItems$ | async;"> // async handles unsubscribe by itself.
<td>{{ item.name }}</td>
</tr>
<table>
If for some reason wanna subscribe in template, then don't forget to unsubscribe, like:
const listSubcription = this.getList().subscribe((data) => {
this.listItems = data;});
ngOnDestroy() {
listSubcription.unsubscribe();
}
// Here is sample code
// Componet Name: list.component.ts
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { NgZone} from '@angular/core';
import {HttpServiceService} from './../http-service.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {
constructor(
private http: HttpServiceService,
private zone: NgZone
) { }
brews: object;
ngOnInit(): void {
this.http.getPeople().subscribe(data => {
this.brews = data;
alert(JSON.stringify(this.brews)); // Diplay
console.log(this.brews);
});
}
}
// Here is my http service
// Componet Name: list.component.ts
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class HttpServiceService {
constructor() { }
getPeople(): Observable<any>{
const peopleArray = [{
firstName: 'Al',
lastName: 'Moje',
age: 63
}];
return of(peopleArray);
}
}