I'm starting on the Observable topic and I found the following situation:
In my servicio.ts
I get a list of books:
URL_API = 'http://localhost:4000/books';
getBooksWithAuthorName() {
return this.http.get<Book[]>(this.URL_API + 'AuthorName');
}
In my componente.ts
I call the service:
bookList$: Observable<Book[]>;
constructor(public bookService: BookService) { }
ngOnInit(): void {
this.getBooksWithAuthorName();
}
getBooksWithAuthorName(){
this.bookList$ = this.bookService.getBooksWithAuthorName();
}
Here componente.html
is where I loop through the list with a ngFor
:
<div *ngFor="let book of bookList$ | async">
<mat-card>
<mat-card-header>
<mat-card-title>{{ book.name }}</mat-card-title>
<mat-card-subtitle>{{ book.price | currency }}</mat-card-subtitle>
</mat-card-header>
<div class="crop-image">
<img [src]="linkImg(book.url_image)" alt="">
</div>
<mat-card-content>
<p>{{ book.description | slice:0:10 }}</p>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary">Agregar al carrito</button>
</mat-card-actions>
</mat-card>
</div>
So far everything works fine but my query is:
In the event that you get an error getting the list in my componente.ts
, I'd like to be able to report it. Try to do it this way:
getBooksWithAuthorName(){
// marca un error de esta forma
this.bookList$ = this.bookService.getBooksWithAuthorName()
.subscribe(
res => {
console.log('Todo correcto');
},
err => console.error('Hay un error al obtener la lista')
);
}
But Angular informs me of the following error:
Type 'Subscription' is missing the following properties from type 'Observable<Book[]>': _isScalar, source, operator, lift, and 6 more.
Add an
pipe()
observable to handle the error.another way of doing error handling may be similar to the way you proposed. In addition, it is recommended that the variable is not an Observable type so that you can manipulate the object easily and directly.