Reputation: 185
The component.ts file
import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http'
import {Observable} from 'rxjs';
import { error } from 'selenium-webdriver';
import { HttpEventType } from '@angular/common/http/src/response';
interface Todo {
result: string[];
}
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
constructor(private http: HttpClient) { }
results: String[];
ngOnInit(): void {
this.http.get<Todo>('http://localhost:3000/todos').subscribe(data => {
this.results = data.result;
console.log(data);
}, (err: HttpErrorResponse) => {
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.log('An error occurred:', err.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
}
}
);
}
}
The component.html file
<div>Works</div>
<ul>
<li *ngFor="let result of results">{{result.text}}</li>
</ul>
I get a HTTP 304 Status code and the returned data is an array of Objects. The json data returned by the Http response:
0: Object { _id: "5a53460339ff2c2488a7bee1", text: "Invade the north tower", __v: 0, … }
1: Object { _id: "5a53464539ff2c2488a7bee2", text: "Collect invisibility rune from Dunaki", __v: 0, … }
2: Object { _id: "5a53465b39ff2c2488a7bee3", text: "Meet Shinoko", __v: 0, … }
3: Object { _id: "5a53585a62ce2331a889556e", text: "xyz", __v: 0, … }
4: Object { _id: "5a5450ce486ddb1e184567ae", __v: 0, date: "2018-01-09T05:19:10.713Z" }
The data is retrieved and stored in the component's results
array, but it is not displayed in the html.
While observing the console, I noticed that the html was rendered first and the response was received after that. But I have mentioned the retrieval logic in the ngOnInit().
Please guide me, thank you!
Upvotes: 1
Views: 693
Reputation: 60528
Shouldn't this line:
this.results = data.result;
Be just this:
this.results = data;
You are showing just data
in the console.log and I don't see that it has a result
property?
UPDATE from comments below: This is the code from the example linked in the comments to this post:
http.get<ItemsResponse>('/api/items').subscribe(data => {
// data is now an instance of type ItemsResponse, so you can do this:
this.results = data.results;
});
Upvotes: 1
Reputation: 55
You must fill list in ngAfterViewInit() method. That's why ngOnInit works first. And after HTML has been loaded, ngAfterViewInit works.
Upvotes: 0