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!
this.results = data.result, since the data had noresultproperty.