I'm trying to build my first web application using angular and Nestjs. when I try to get data from the server error was shown in the browser console. any help with that please.
core.js:4081 ERROR TypeError: this.books is not iterable
at SafeSubscriber._next (book.service.ts:23)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
at SafeSubscriber.next (Subscriber.js:122)
at Subscriber._next (Subscriber.js:72)
at Subscriber.next (Subscriber.js:49)
at MapSubscriber._next (map.js:35)
at MapSubscriber.next (Subscriber.js:49)
at FilterSubscriber._next (filter.js:33)
at FilterSubscriber.next (Subscriber.js:49)
at MergeMapSubscriber.notifyNext (mergeMap.js:72)
angular
book.service.ts
import { Book } from './book.model';
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BookService {
private books: Book[] = [];
private booksUpdated = new Subject<Book[]>();
constructor(private http: HttpClient) {
}
getBooks(){
this.http.get<{books:Book[]} >('http://localhost:3000/books')
.subscribe((bookData) =>{
this.books = bookData.books;
this.booksUpdated.next([...this.books]);
});
}
getBookUpdateListener(){
return this.booksUpdated.asObservable();
}
addBook( book_name: string, author: string){
const book: Book = {book_ref_no: null, book_name: book_name, author: author, category: null};
this.books.push(book);
this.booksUpdated.next([...this.books]);
}
}
response from the server
[{"book_ref_no":4,"book_name":"ice and fire","author":"jrr martine","category":"HISTORY"}]
can anyone please help me to fix this. please tell me the provided data is not enough to figure out a solution,
Welcome to Angular and NestJS.
Your backend controller's response seems to be:
[
{ book 1...},
{ book 2...},
...
]
So you should simply type your HttpClient.get
response as Book[]
.
getBooks(){
this.http.get<Book[]>('http://localhost:3000/books').subscribe(books => {
this.books = books;
this.booksUpdated.next(books);
});
}