让前端飞Web前端之路前端开发

rxjs-错误处理

2019-06-26  本文已影响1人  bugWriter_y
timg.jpg

catchError

当外部源发生错误时,处理错误同时返回一个新的数据源作为返回值。例如http请求的错误处理。

import { HttpClient } from "@angular/common/http";
import { catchError } from "rxjs/operators";
import { of } from "rxjs";

constructor(private http: HttpClient) {}
ngOnInit() {
  this.http
    .get<[]>(`http://localhost:4000/users`)
    .pipe(
      catchError(err => {
        console.error("http请求错误统一处理", err);
        return of([]);
      })
    )
    .subscribe(users => {
      console.log(users);
    });
}

retry

当发生错误的时候进行重试。接受一个数字,代表重试次数。例如http请求的错误处理。

import { HttpClient } from "@angular/common/http";
import { catchError, retry } from "rxjs/operators";
import { of } from "rxjs";
constructor(private http: HttpClient) {}
ngOnInit() {
  this.http
    .get<[]>(`http://localhost:4000/users`)
    .pipe(
      retry(3),
      catchError(err => {
        console.error("http请求错误统一处理", err);
        return of([]);
      })
    )
    .subscribe(users => {
      console.log(users);
    });
}
上一篇下一篇

猜你喜欢

热点阅读