Search code examples
javascriptangulartypescriptionic-frameworkngrx

TypeScript: NgRx effect to trigger an action


Am new to NgRx most of my code is working fine but am stuck at this particular one and I will be need your help .

When Login Effect as been triggered and its successfully sent to LoginSuccess am trying to save to localstorage and trigger another action.

Below is my sample code

Effect

    @Effect({ dispatch: false })
    LogInSuccess$: Observable<any> = this.actions$.pipe(
        ofType<businessActions.LogInSuccess>(
            businessActions.AuthActionTypes.LOGIN_SUCCESS
        ),
        map((action: businessActions.LogInSuccess) => {
            localStorage.setItem('token', JSON.stringify(action.payload));
            this.navCtrl.navigateRoot('/home');
        }), map(
            () => new businessActions.LoadBiz()
        )
    );

Solution

  • I presume from your comments and code you are trying to implement some UI behavior upon response from some service (LoginService). That code is fine for a library or for a service. But at some point you need to know the result, at some point you need to subscribe() to the observable you are creating in order to know it result

    Make a subscribe() call at the end. Otherwise your observable will never materialize.

    UPDATE

    Besides the subscribe() call, you need to navigate to /home url and then in the component that handle that route load your business: new businessActions.LoadBiz()

    your code should look to me like:

    @Effect({ dispatch: false })
    LogInSuccess$: Observable<any> = this.actions$.pipe(
        ofType<businessActions.LogInSuccess>(
            businessActions.AuthActionTypes.LOGIN_SUCCESS
        ),
        map((action: businessActions.LogInSuccess) => {
            localStorage.setItem('token', JSON.stringify(action.payload));
        })
    ).subscribe(() => this.navCtrl.navigateRoot('/home'));
    
    

    then where ever you handle /home route, in the init() method of the component new businessActions.LoadBiz() or better yet, extract businessActions logic into a service, inject the service and call: businessActions.LoadBiz() no need to call new in your UI then.