簡體   English   中英

如何在catcherror中從訂閱中返回已翻譯的消息?

[英]How do I return a translated message from a subscription in a catcherror?

我希望我的catch錯誤返回一個新的LoginFailure操作,但是帶有來自翻譯服務訂閱的消息。 這個實現給了我:

類型'(error:any)=> void'的參數不能賦給類型'(err:any,caught:Observable)=> ObservableInput <{}>'的參數。

@Effect()
  login$ = this.actions$.ofType<Login>(AuthActionTypes.Login).pipe(
    map(action => action.payload),
    exhaustMap(auth =>
      this.authService.login(auth).pipe(
        map(data => new LoginSuccess({ data: data })),
        catchError(error => {
          this.translateService
          .get('LoginErrorMessage')
          .subscribe((res: string) => {
            of(new LoginFailure(res));
          });
        }
        )
      )
    )
  );

任何幫助,將不勝感激。

  1. 您收到該錯誤,因為您沒有從catchError返回任何catchError
  2. 你必須返回一個Observable而不是訂閱,所以使用mergeMap() (展平)Observable而不是Subscription。
  3. 根據您希望此請求的接收者將消息視為成功或錯誤,您必須返回錯誤或成功。

      @Effect() login$ = this.actions$.ofType<Login>(AuthActionTypes.Login).pipe( map(action => action.payload), exhaustMap(auth => this.authService.login(auth).pipe( map(data => new LoginSuccess({ data: data })), catchError(error => { return this.translateService .get('LoginErrorMessage') .pipe( mergeMap((res: string) => { return of(new LoginFailure(res)); // to get it in success callback // or return throwError(new LoginFailure(res)) // to get it in error call back }); ) } ) ) ) ); 


更新

如果您在獲得登錄錯誤后不想調用另一個observable,則無需使用展平運算符。 法線map()會做。

  @Effect() login$ = this.actions$.ofType<Login>(AuthActionTypes.Login).pipe( map(action => action.payload), exhaustMap(auth => this.authService.login(auth).pipe( map(data => new LoginSuccess({ data: data })), catchError(error => { return this.translateService .get('LoginErrorMessage') .pipe( map((res: string) => { if (you want the response in success callback) { return new LoginFailure(res); } else { // if you want it in error throw "your error"; // say, {error: "I am Error"} } }); ) } ) ) ) ); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM