【问题标题】:Angular-NGRX: Catch HTTP Error in the componentAngular-NGRX:在组件中捕获 HTTP 错误
【发布时间】:2022-01-11 15:38:50
【问题描述】:

我已经在我的 Angular 项目中实现了存储,我能够捕获和处理successSelector,但是在来自后端的 HTTP 错误时,errorSelector 没有捕获到任何数据。

在 effects.ts 中捕获错误如下

    private postupload() {
    return this.actions$.pipe(
        ofType(uploadActionTypes.uploadRequestAction),
        map(action => action.fileUpload),
        switchMap((fileUpload: any) => this.uploadService.postUploadfile(fileUpload)),
        map((data: any) => uploadActionTypes.uploadSuccessAction({ data })),
        catchError((error: any) => of(uploadActionTypes.uploadFailureAction({ error }))
        )
    );
    
}

errorSelector 在 selector.ts 中声明如下

export const uploadErrorSelector = createSelector(
uploadStateSelector,
(state: IuploadState) => state.uploadFileResponse.Errors
);

服务.ts

  public postUploadfile(fileinfo: any): Observable<any> {

    let savefileUploadUrl = `${this.apiBaseURL + UploadApiEndPointUrl.fileUploadUrl}`;
    return this.http.post<any>(savefileUploadUrl, fileinfo).pipe(
      map((response: Response) => response),
      catchError(this.errorHandler)
   )
  }
     errorHandler(error: HttpErrorResponse) {
     return Observable.throw(error);
  }
  }

在component.ts中调用了服务的调度,

  postUploadFileSubscription() {
    this.postUploadFileSubscription$ = this.store.select(UploadSelector.uploadSelector).subscribe(
      response =>{
        console.log("response:", response);
      if(response.hasOwnProperty('Data')){
        if (typeof (response.Data) !== 'undefined' ) {
          //console.log("response:", response);
            // Business actions
        
        }
        else {
        }
  
      }
    },  error => {
      
      this.errorMsg = error.error.Message;
   
    },
    () => {
      console.log('POST upload  - now completed.');
    })
    
  }

当服务器的状态为 200 时,响应被捕获,但当有错误响应时,它不会被捕获。

请建议如何捕获 httpError 响应并将其处理到 UI。

【问题讨论】:

    标签: angular typescript ngrx-store


    【解决方案1】:

    您可以删除所有在服务器调用后放置的catchErrors。

    1. 使用intereptor 处理 HTTP 错误。

    2. (response) =&gt; {} 之后使用(error) =&gt; {} 来处理组件中的错误。

    您也不需要pipe 来映射响应。像这样使用它:

    return this.http.post<Response>(savefileUploadUrl, fileinfo);
    

    在你的组件中:

    this.store.select(UploadSelector.uploadSelector).subscribe((res) => {}, (err) => {});
    

    【讨论】:

    • 您好@skyBlue,我根据您的建议做了以下更改 1. 删除了“管道”并使用响应 2 发布了 http 帖子。使用了 '.subscribe((res) => {} , (err) => {});'但是我注意到仍然没有发现错误,它在没有存储/调度实现的情况下运行良好
    • 嗯,有什么好的结果吗? @KiranNarayan
    • 不,仍然没有发现错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多