rxjs-错误处理

作者: bugWriter_y | 来源:发表于2019-06-26 11:20 被阅读1次
    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);
        });
    }
    

    相关文章

      网友评论

        本文标题:rxjs-错误处理

        本文链接:https://www.haomeiwen.com/subject/omnqcctx.html