捕获和释放

我们还可以选择使用.catch运算符。它允许我们捕获现有流上的错误,做一些事情然后传递异常。

  1. import { HttpClient } from "@angular/common/http";
  2. import { Injectable } from '@angular/core';
  3. import { Observable } from 'rxjs/Rx';
  4. @Injectable()
  5. export class SearchService {
  6. constructor(private http: HttpClient) {}
  7. search(term: string) {
  8. return this.http.get('https://api.spotify.com/v1/dsds?q=' + term + '&type=artist')
  9. .catch((e) => {
  10. return Observable.throw(
  11. new Error(`${ e.status } ${ e.statusText }`)
  12. );
  13. });
  14. }
  15. }

View Example

它还允许我们检查错误并决定采取哪条路由。例如,如果我们遇到服务器错误,则使用缓存版本的请求,否则重新抛出。

  1. @Injectable()
  2. export class SearchService {
  3. ...
  4. search(term: string) {
  5. return this.http.get('https://api.spotify.com/v1/dsds?q=' + term + '&type=artist')
  6. .map((response) => response.json())
  7. .catch((e) => {
  8. if (e.status >== 500) {
  9. return cachedVersion();
  10. } else {
  11. return Observable.throw(
  12. new Error(`${ e.status } ${ e.statusText }`)
  13. );
  14. }
  15. });
  16. }
  17. }