NgRX effects - Type 'Observable' is not assignable to type 'Observable'

前端 未结 9 1098
你的背包
你的背包 2020-12-16 10:12

While working with NgRX 8 my colleagues and me are frequently facing a weird error message when implementing the effects.

Type \'Observable

9条回答
  •  庸人自扰
    2020-12-16 10:36

    I had the exact same issue and in my case it was because of wrongly placed braces and a missing import.

    Here is what I did to debug and solve it.

    Split the inner pipe-able function into individual functions. This is the foremost step for me because of the complex syntax and auto complete braces from vscode, sometimes a brace exists in wrong place and it's not easy to find. This also solves almost all other problems (missing imports, incorrect return types etc) as the code to debug is much smaller and vscode highlights this individual error from the sub function.

    This is what I had before

        performLogin$ = createEffect(() => 
           this.actions$.pipe(
               ofType(performLogin),
               mergeMap(() => this.loginService.performLogin().pipe(
                   map(() => loginSuccess())
               )))
        );
    
    

    Changed this to below

     performLogin$ = createEffect(() => 
           this.actions$.pipe(
               ofType(performLogin),
               mergeMap(() => this.performLogin()),
               catchError((error ) => { console.log("HELLO"); return EMPTY})
           )
        );
    
        performLogin() {
            return this.loginService.performLogin()
            .pipe(map(() => loginSuccess()));
        }
    
    

    Also a bonus I got from this approach is that the catchError block on the inner pipe does not get triggered (as per effects example it should work). Hence had to include it in the outer pipe-able block. Here the error is caught and works as expected. But still figuring out why it does not work.

    Just to sum it up, the login service does the following (throw error or return Observable of true)

    //login.service.ts
    
    performLogin() : Observable {
            throw "Something went wrong";
            //return of(true);
        }
    
    

    Hope this helps.

提交回复
热议问题