异步进行角度可观察的错误处理

时间:2018-10-30 11:45:01

标签: angular

我有一个收集数据的服务和一个向其显示代码的组件,如下所示:

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>

现在我想处理HTTP错误(例如404)。但是我不知道如何在不添加订阅功能的情况下正确添加错误处理程序。

1 个答案:

答案 0 :(得分:5)

使用catchError处理错误。

import { catchError } from 'rxjs/operators';

findAllBooks(): Observable<Book[]> {
    return this.http.get<Book[]>('api/books').pipe(
      catchError(error =>  // handle the errore)
    )
  }