【问题标题】:not able to redirect using handlerror无法使用 handlererror 重定向
【发布时间】:2020-12-28 14:27:51
【问题描述】:

当响应数据出现“401”错误时,我正在尝试重定向到错误组件,以下是我的代码 但它没有处理错误。我试图重定向到外部 url 但没有运气。 请指导,提前感谢

Service.ts:-

public searchGroups(searchReviewData: SurveillanceReviewSearchViewModel): Observable<SurveillanceReviewSearchViewModel> {
    this._urlSurveillanceDetails = this.baseHref + "/ReviewProfile/SearchGroups";
    const headers: HttpHeaders = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    let getData = this.http.post<SurveillanceReviewSearchViewModel>(this._urlSurveillanceDetails, searchReviewData, { headers: headers })
      .pipe(
        catchError(this.handleError)
      );
    return getData;
  }


  handleError(data: any) {
    if (data instanceof ErrorEvent) {

    }
    else {
      switch (data.errorResponse.httpStatusCode) {
       case 401:
       this.router.navigate(['error', 'unauthorized']);
         break;       

      }
    } 
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later:' + JSON.stringify(data.errorResponse.httpStatusCode));

  }

Component.ts

searchGroups(searchReviewData: SurveillanceReviewSearchViewModel) {
    this._surveillanceService.searchGroups(searchReviewData).subscribe(data => {
      if (data != undefined) {
        this.reviewData = data;
        if (data.reviews != null) {
          if (data.reviews.length == 1) {                
            this.pagerSelectedData = data.reviews;
            this.loading = false;                

          }
        }
        else {
          this.loading = true;
        }
      }
    });
  }

来自 MVC 控制器的ResponseJson:

{
    "loggedInUser": {
        "v2020UserId": "kdevisenakanthan"
    },
    "errorResponse": {
        "errorCode": null,
        "transactionId": null,
        "httpStatusCode": 401
    }
}

【问题讨论】:

  • 如果您的代码尝试执行重定向,它将崩溃。永远不要将未绑定的方法作为回调传递。使用箭头函数或.bind

标签: angularjs angular typescript angularjs-directive angular-ui-router


【解决方案1】:

好像用data.error instanceof ErrorEventdata.status

在这里查看文档https://angular.io/api/common/http/HttpErrorResponse

【讨论】:

  • 谢谢,我添加了响应 json 。我需要检查“errorResponse”子对象中的状态,请指导我
猜你喜欢
  • 1970-01-01
  • 2010-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多