I'am newbie in Angular, but for study i want to get data from API. However, I wait about 2 seconds for the response from the API, so my page loads and the variable to which I want to save the result of the sent request to the API is not displayed.
My API return JSON as List:
[
{
"idWebsite": Guid,
"name": "string",
"url": "string",
"location": "string",
"enviroment": "string",
"lastTestedByBenchmark": "string"
},
{
"idWebsite": Guid,
"name": "string",
"url": "string",
"location": "string",
"enviroment": "string",
"lastTestedByBenchmark": "string"
}
]
My Angular code:
export class AppComponent {
title = 'APITest';
Websites = new Array<WebsitesListViewModel>();
constructor(private http: HttpClient) {
}
ngOnInit(){
this.http.get<Array<WebsitesListViewModel>>('APIUrl').subscribe(data=>{
this.Websites=data;
})
}
}
export class WebsitesListViewModel{
IdWebsite:string = "";
Name:string="";
Url:string=""
Location:string="";
Enviroment:string="";
LastTestedByBenchmark:string="";
}
I read that in that case Observable should be used. Using the tutorial and documentation I wanted to do it, but the variable nested in widomu still doesn't refresh after receiving response.
export class AppComponent {
title = 'APITest';
Websites$ = new Array<WebsitesListViewModel>();
constructor(private http: HttpClient) {
//this.GetAll().subscribe(result=>this.Websites = result);
this.GetAll().subscribe(response=>{
this.Websites$ = response
console.log(this.Websites$)
})
console.log(this.Websites$)
}
GetAll(): Observable<WebsitesListViewModel[]> {
return this.http.get<WebsitesListViewModel[]>('APIURL')
}
}
export class WebsitesListViewModel{
IdWebsite:string = "";
Name:string="";
Url:string=""
Location:string="";
Enviroment:string="";
LastTestedByBenchmark:string="";
}
P.S. If in Angular constructor -> subscribe method I add console.log(Websites) in console i got API result
I think you need an async pipe,
here is how you do it in your HTML,
<div *ngFor="let data of Websites | async">{{data.url}}</div>