I have a service that collects data and a component to show it the code is as follows:
books.service:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Book} from '../model/book';
@Injectable()
export class BooksService {
constructor(private http: HttpClient) {
}
findAllBooks(): Observable<Book[]> {
return this.http.get<Book[]>('api/books');
}
}
list-books.component.ts:
import {Component, OnInit} from '@angular/core';
import {BooksService} from '../../services/books.service';
import {Observable} from 'rxjs/Observable';
import {Book} from '../../model/book';
@Component({
selector: 'app-list-books',
templateUrl: './list-books.component.html',
styleUrls: ['./list-books.component.css']
})
export class ListBooksComponent implements OnInit {
books: Observable<Book[]>;
constructor(private booksService: BooksService) {
}
ngOnInit() {
this.books = this.booksService.findAllBooks();
}
}
list-books.component.html:
<table class="table table-striped table-hover">
<tr *ngFor="let book of books | async">
<td>
{{book.title}}
</td>
</tr>
</table>
Now I would like to handle HTTP Errors (e.g. 404). But I don't know how to properly add error handler without adding subscribe function.
BooksService. If you want to show an error message, you need to subscribe in the controller and handle the error.asyncpipe doesn't know how you want to handle the error...// handle the errorefrom @Sachila toof(booksMock)