简体   繁体   中英

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

I want my catch error to return a new LoginFailure action but with a message that comes from the subscription of the translate service. This implementation is giving me:

Argument of type '(error: any) => void' is not assignable to parameter of type '(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));
          });
        }
        )
      )
    )
  );

any help would be appreciated.

  1. You get that error because you aren't returning anything from catchError .
  2. You got to return an Observable not a subscription, so use mergeMap() (to flatten) the Observable instead of Subscription.
  3. Depending you want the receiver of this request to get the message as a success or an error you have got to return an error or a success.

      @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 }); ) } ) ) ) ); 


Update

In case you don't want to call another observable after you get a Login Error, there is no need of using a flattening operator. A normal map() will do.

  @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"} } }); ) } ) ) ) ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM