HTTP 响应错误处理 Angular 应用程序

Jig*_*try 2 typescript angular angular6

我有一个 data.json 文件,如下所示。

[
    {"value":1},
    {"value":2},
    {"value":3},
    {"value":3}
]
Run Code Online (Sandbox Code Playgroud)

& 我正在使用 Http 来获取数据。数据正常传输,但是如果我的服务器关闭了,那么它会抛出错误,我想向用户显示一些自定义消息而不是该错误。下面是我获取数据的函数。

 data: any;

  getData() {
    this.http.get('http://localhost/php/data.json').subscribe((res) => {
      this.data = res;
      console.log(this.data);
    })
  }

  ngOnInit() {
    this.getData();
  }
Run Code Online (Sandbox Code Playgroud)

Ant*_*sss 6

  getData() {
    this.http.get('http://localhost/php/data.json').subscribe((res) => {
      this.data = res;
      console.log(this.data);
    },(err:HttpErrorResponse)=>{handle your error here});
Run Code Online (Sandbox Code Playgroud)

subscribe 接受错误处理回调作为第二个参数。您可以在此处查看 API 详细信息

https://angular.io/api/common/http/HttpErrorResponse

  • 这是正确的,但我建议用户 `.catch( ( err: Error) => { handleErrors; } ) ` 因为您可以将代码错误处理到响应函数中 (2认同)

Sac*_*aka 6

您还可以使用 rxjs 提供的 catchError 运算符

import {catchError} from 'rxjs/operators'

this.http.get('http://localhost/php/data.json')
    .pipe ( 
       catchError((error) => // handle the error here; )
     )
    .subscribe((res) => {
      this.data = res;
      console.log(this.data);
    })
Run Code Online (Sandbox Code Playgroud)