Search code examples
angulartypescriptfrontendngrxngrx-effects

'Observable' is not assignable to type 'EffectResult'


I am working on a project that uses angular 12 and NGRX.

I get this error:

Error: src/app/auth/state/principal.effects.ts:17:30 - error TS2345: Argument of type '() => Observable<unknown>' is not assignable to parameter of type '() => EffectResult<Action>'.
  Type 'Observable<unknown>' is not assignable to type 'EffectResult<Action>'.
    Type 'Observable<unknown>' is not assignable to type 'Observable<Action>'.
      Type 'unknown' is not assignable to type 'Action'.
  

On this code block:

getToken$ = createEffect(() => {
    return this.actions$
      .pipe(
        ofType(PrincipalActions.login),
        switchMap(action => this.loginService.getToken(action.credentials)
          .pipe(
             map(authentication  => {alert("success from effects"); return EMPTY}),
             catchError(error => {console.log(error); return error;})
          )
      ));
  });

And here is the login service:

  export class LoginService {

     constructor(private http: HttpClient) { }

    getToken(credentials: Credential): Observable<Principal> {
       return this.http.post<Principal>(environment.baseUrl + '/login', JSON.stringify(credentials) )
    }
 }

Any idea why I get the error above and how to fix it?


Solution

  • Effect should return a new Action and from what I see your effect does not return it. If you want to do something in the effect, without dispatching a new Action, you can specify this as another paramater in createEffect function. See Non-dispatching Effects

    getToken$ = createEffect(() =>
      this.actions$.pipe(
        ofType(PrincipalActions.login),
        switchMap(action => this.loginService.getToken(action.credentials)
          .pipe(
            tap(authentication => alert("success from effects")),
            catchError(error => {console.log(error); return error;})
          )
        ),
      ), { dispatch: false});
    

    Or replace EMPTY and error with actions, if you want to process getToken result somehow with NgRx.

      map(authentication  => {
        alert("success from effects"); 
        return PrincipalActions.loginSuccess(...);
      }),
      catchError(error => {
        console.log(error); 
        return PrincipalActions.loginError(...);
      })