1

I've created a small application that permits a user to login and logout using ngrx state. The user login works well. I can login and using an AuthGuard I can check if the user is still login in the app after the refresh of the page. Now I should logout the user. This is my action:

export const LOGOUT = '[Auth] Logout';
export const logout = createAction(
    LOGOUT
  );

than the effect

logout$ = createEffect(() =>
        this.actions$
            .pipe(
                ofType(userActions.logout),
                tap(action => {
                    localStorage.removeItem('user');
                    this.router.navigate(['login']);
                })
            )
    ,{dispatch: false});

and of ourse the reducer:

export const authReducer = createReducer (
    defaultUser,

    on(userActions.logout, (state, action) => {
        return {
            user: undefined
        }
    })
)

After that, I can create in my component a logout button with this

onLogout(){
    this.store.dispatch(logout())
  }

I expect that the dispatch call the action and then the effect. Inside the effect it should remove the user from the localStorage. but even if I try to debug the effect it doesn't enter inside the tap operator. It doesn't remove the item and it doesn't redirect to login. Is there anything else i missed here?

Atlas91
  • 5,754
  • 17
  • 69
  • 141

1 Answers1

1

As mentioned in official doc,

After you've written your Effects class, you must register it so the effects start running. To register root-level effects, add the EffectsModule.forRoot() method with an array of your effects to your AppModule.

If in this case, the effect module is called AuthEffect, we should have this code snippet in AppModule:

import { EffectsModule } from '@ngrx/effects';
import { AuthEffects } from './effects/auth.effects';

@NgModule({
  imports: [
    EffectsModule.forRoot([ AuthEffects ])
  ],
})
export class AppModule {}

If authentication is managed inside a feature module, you should use in place this code, to register AuthEffect inside AuthModule:

import { EffectsModule } from '@ngrx/effects';
import { AuthEffects } from './effects/auth.effects';

@NgModule({
  imports: [
    EffectsModule.forFeature([ AuthEffects ])
  ],
})
export class AuthModule {}
Thierry Falvo
  • 5,892
  • 2
  • 21
  • 39