【问题标题】:Handle status in angular以角度处理状态
【发布时间】:2020-01-18 10:26:36
【问题描述】:

我在 Angular 7 中有以下内容。

public deleteId(pId){
    return this.http.delete<any>(this.deleteUrl(pId), {observe: 'response'})
      .pipe(catchError(this.handleError));
  }

删除方法(我在 response.status 中要 202 代码)

public deleteMethod(): void {
    this.service.deleteId(this.id)
      .subscribe(response => {

       console.log(`Delete response ` , response);

        if(response.status === 200) {
          console.log('Deleted successfully');
        }
       else if(response.status === 202) {
          console.log('something else'); // I am not getting response.status here
        }
    });
  }

我正在正确获取状态代码 200,但是 202 我正在使用 handleError 方法。我想要 202 作为回应。我怎样才能得到它?

private handleError(error: HttpErrorResponse) {
  //It sends me to this function.
}

【问题讨论】:

  • 如果出现 202 状态,您能否在 handleResponse 方法中包含 error 变量包含的内容?
  • @Igor 你是什么意思?我想这是你要求的response.status
  • @ketan 真的不清楚你在问什么。你能详细说明一下吗?
  • @PaoloCasciello 我编辑了。当我运行调用的应用程序 API 并且如果响应状态为 202 时,它会将我发送到 handleError 函数而不是 .subscribe(response

标签: angular typescript angular-httpclient


【解决方案1】:

最后我得到了以下解决方案:

public deleteId(pId){
    return this.http.delete<any>(this.deleteUrl(pId), {observe: 'response', responseType: 'text' as 'json'})
      .pipe(catchError(this.handleError));
 }

已添加, responseType: 'text' as 'json'

【讨论】:

    【解决方案2】:
    public deleteMethod(): void {
    this.service.deleteId(this.id)
      .subscribe(response => {
    
       console.log(`Delete response ` , response);
    
        if(response.status === 200) {
          console.log('Deleted successfully');
        }
      },
      err => {
        console.log(err.status); // ----> Here's your error
        if(err.status === 202) {
          // do your stuff
        }
      }
    );
    

    }

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2022-10-13
    • 2017-01-31
    • 2019-02-10
    • 2023-02-17
    相关资源
    最近更新 更多