如何在Angular 8中解决Observable中的catch错误?

22

我编写了错误处理程序,但在 catch 中出现了错误。undefined method。

这是我的 serivce.ts 代码。

import { Injectable } from "@angular/core";
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { user } from "./user";
import { Observable } from "rxjs";
import "rxjs/add/operator/catch";
import "rxjs/add/Observable/throw";
@Injectable({
  providedIn: "root"
})
export class DemoService {
  private url: string = "/assets/demo/user.json";
  constructor(private http: HttpClient) {}

  getuserdetails(): Observable<user[]> {
    return this.http.get<user[]>(this.url).catch(this.errorHandler);
  }
  errorHandler(error: HttpErrorResponse) {
    return Observable.throw(error.message || "server error.");
  }
}

这是我的app.component.ts文件代码

 public userdetails = [];
  public errorMsg;
  constructor(private user: DemoService) {}
  ngOnInit() {
    this.user
      .getuserdetails()
      .subscribe(
        $data => (this.userdetails = $data),
        error => (this.errorMsg = error)
      );
  } 

我在catch中出现了错误,错误信息是“属性'catch'不存在于类型'Observable'上”。


1
你可以像在app.componentngOnInit中那样做,例如error => (this.errorMsg = error),但是为什么要在两个地方捕获错误?你应该只在service中捕获它。 - jitender
在 service.ts 文件中,我定义了 catch 和 (this.errorMsg=error)。在我的 app.component.ts 文件中,使用这个文件来在客户端显示数据和错误信息。 - Ashruti
可能是重复问题:https://dev59.com/L1YO5IYBdhLWcg3wU_6M#46021824 - ngShravil.py
5个回答

19
你可以在rxjs/operators中使用catchError来实现此功能。可按以下方式尝试。
import { catchError } from 'rxjs/operators';

export class DemoService {

    getuserdetails(): Observable<user[]> {
        return this.http.get<user[]>(this.url)
            .pipe(catchError(this.errorHandler))
    }
    errorHandler(error: HttpErrorResponse) {
        return Observable.throw(error.message || "server error.");
    }
}

4
你好。我有大约与你在这个答案中发布的相同的代码,但是 catchError() 方法不起作用。即使服务器返回的是 500 错误码,它也不会抛出任何异常。 - WitnessTruth

8
在rxjs的最新版本中,你应该使用:
return return this.http.get<user[]>(this.url)
                  .subscribe((r:Author) => console.log("GOOD"),
                                    err => console.log("ERROR))

1
已弃用 https://rxjs.dev/deprecations/subscribe-arguments - GarryMoveOut

5
import { Observable, throwError } from 'rxjs';
import { catchError, } from 'rxjs/operators';

return this.http.get<user[]>(this.url).pipe(catchError(this.errorHandler))

errorHandler(error: HttpErrorResponse) {
    return throwError(error.message || "server error.");
}

4

在可观测对象中捕获错误的最佳方法是:


this.http.get<user[]>(this.url).pipe(
   tap(),
   catchError(err => { return this.errorHandler(err) }
)

如果this.http.get()是一个Promise,请像您在代码中所做的那样保留它,.catch(...)没问题。尝试将catchError(...)放在管道末尾或在使用finalize(..)之前。

在Observable之前,没有.pipe(),您需要像在Promises中链接操作一样,因此它们将.then()更改为flatMap(),并将.catch()更改为catchError()以便程序员知道它是Observable还是Promise。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接