I'm trying to display JSON response but I get this error: core.js:6185 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed.
How can I solve this issue? How can I convere it to array ?
TS
export interface Book {
id: number,
book_name: string,
book_issue: Date,
}
Service.ts
export class BookApiService {
private bookUrl = "http://127.0.0.1:5000/books"
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
constructor (private http: HttpClient){}
getBook(): Observable<Book[]> {
return this.http.get<Book[]>(this.bookUrl ,this.httpOptions)
.pipe(
catchError(this.errorHandler)
)
}
errorHandler(error) {
let errorMessage = '';
if(error.error instanceof ErrorEvent) {
errorMessage = error.error.message;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
return throwError(errorMessage);
}
template
<ul *ngFor="let book of books">
<li>{{book.book_name}}</li>
</ul>
Component
export class AppComponent implements OnInit {
title = 'app';
books: Book[] = [];
constructor(public rs : BookApiService){}
ngOnInit(): void {
this.rs.getBook().subscribe((data: Book[])=>{
this.books = data;
console.log(this.books);
})
}
Backend API Response:
{"books":[{"book_issue":"Fri, 13 Mar 2020","book_name":"Book1","id":1},
{"book_issue":"Fri, 13 Mar","book_name":"Book2", "id":2}],
"success":true}
and this is the console log: console Log