I have a method that uses a service to get a list of books, i needed a second method that uses the list of books to get one book by filtering it by id. The two methods are called in "ngOnInit" of the same component. What i get is in the second method uses the books list before it gets its results.
I fixed the issue by calling the second method in the first inside the results of .subscribe, then calling only the first in ngOnInit. I didn't find the solution quite satisfying, i want a more general and organised way ...
export class BookComponent implements OnInit {
public books: Book[];
public book: Book;
public id;
public sub;
constructor(private activatedRoute: ActivatedRoute, private router: Router, private bookService: BookService) {}
getBooks() {
this.bookService.getBooks().subscribe(
result => {
this.books = result;
}
);
}
findById() {
this.sub = this.activatedRoute.paramMap.subscribe(params => {
console.log(params);
this.id = params.get('id');
this.book = this.books.find(a => a.id == this.id);
});
}
ngOnInit() {
this.getbooks();
this.findById();
}
}
Here is the error i get:
ERROR TypeError: Cannot read property 'find' of undefined