调用this.store.dispatch(new Login({authToken:user.accessToken}))时如何更新减速器状态Angular 8

问题描述 投票:1回答:1

当重新加载我的URL localhost:4200 /时,@ ngrx / store / reducer-update起作用并且我的存储状态

   // Angular
import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
// RxJS
import { filter, mergeMap, tap, withLatestFrom } from 'rxjs/operators';
import { defer, Observable, of } from 'rxjs';
// NGRX
import { Actions, Effect, ofType } from '@ngrx/effects';
import { Action, select, Store } from '@ngrx/store';
// Auth actions
import { AuthActionTypes, Login, Logout, Register, UserLoaded, UserRequested } from '../_actions/auth.actions';
import { AuthService } from '../_services/index';
import { AppState } from '../../reducers';
import { environment } from '../../../../environments/environment';
import { isUserLoaded } from '../_selectors/auth.selectors';

@Injectable()
export class AuthEffects {
   @Effect({dispatch: false})
   login$ = this.actions$.pipe(
       ofType<Login>(AuthActionTypes.Login),
       tap(action => {
           localStorage.setItem(environment.authTokenKey, action.payload.authToken);

           this.store.dispatch(new UserRequested());
       }),
   );

   @Effect({dispatch: false})
   logout$ = this.actions$.pipe(
       ofType<Logout>(AuthActionTypes.Logout),
       tap(() => {
           localStorage.removeItem(environment.authTokenKey);
           this.router.navigate(['/auth/login'], {queryParams: {returnUrl: this.returnUrl}});
       })
   );

   @Effect({dispatch: false})
   register$ = this.actions$.pipe(
       ofType<Register>(AuthActionTypes.Register),
       tap(action => {
           localStorage.setItem(environment.authTokenKey, action.payload.authToken);
       })
   );

   @Effect({dispatch: false})
   loadUser$ = this.actions$
   .pipe(
       ofType<UserRequested>(AuthActionTypes.UserRequested),
       withLatestFrom(this.store.pipe(select(isUserLoaded))),
       filter(([action, _isUserLoaded]) => !_isUserLoaded),
       mergeMap(([action, _isUserLoaded]) => this.auth.getUserByToken()),
       tap(_user => {
           if (_user) {
               this.store.dispatch(new UserLoaded({ user: _user }));
           } else {
               this.store.dispatch(new Logout());
           }
       })
     );

   @Effect()
   init$: Observable<Action> = defer(() => {
       const userToken = localStorage.getItem(environment.authTokenKey);
       let observableResult = of({type: 'NO_ACTION'});
       if (userToken) {
           observableResult = of(new Login({  authToken: userToken }));
       }
       return observableResult;
   });

   private returnUrl: string;

   constructor(private actions$: Actions,
       private router: Router,
       private auth: AuthService,
       private store: Store<AppState>) {

       this.router.events.subscribe(event => {
           if (event instanceof NavigationEnd) {
               this.returnUrl = event.url;
           }
       });
   }
}

首先重新加载我的本地主机:4200,键入NO_ACTION,然后单击登录按钮,割草机this.store.dispatch(new Login({ authToken: user.accessToken }));但是export const initialAuthState: AuthState = { loggedIn: false, authToken: undefined, user: undefined, isUserLoaded: false };loggerIn没有变成true

我的auth.reducer.ts是那个

    // Actions
import { AuthActions, AuthActionTypes } from '../_actions/auth.actions';
// Models
import { User } from '../_models/user.model';

export interface AuthState {
    loggedIn: boolean;
    authToken: string;
    user: User;
    isUserLoaded: boolean;
}

export const initialAuthState: AuthState = {
    loggedIn: false,
    authToken: undefined,
    user: undefined,
    isUserLoaded: false
};

export function authReducer(state = initialAuthState, action: AuthActions): AuthState {
    switch (action.type) {
        case AuthActionTypes.Login: {
            const _token: string = action.payload.authToken;

            return {

                loggedIn: true,
                authToken: _token,
                user: undefined,
                isUserLoaded: false
            };
        }

        case AuthActionTypes.Register: {
            const _token: string = action.payload.authToken;
            return {
                loggedIn: true,
                authToken: _token,
                user: undefined,
                isUserLoaded: false
            };
        }

        case AuthActionTypes.Logout:
            return initialAuthState;

        case AuthActionTypes.UserLoaded: {
            const _user: User = action.payload.user;
            return {
                ...state,
                user: _user,
                isUserLoaded: true
            };
        }

        default:
            console.log(state);

            return state;
    }
}

我的auth.action.ts

    import { Action } from '@ngrx/store';
import { User } from '../_models/user.model';

export enum AuthActionTypes {
    Login = '[Login] Action',
    Logout = '[Logout] Action',
    Register = '[Register] Action',
    UserRequested = '[Request User] Action',
    UserLoaded = '[Load User] Auth API'
}



export class Login implements Action {  
    readonly type = AuthActionTypes.Login;

    constructor(public payload: { authToken: string }) { }
}


export class Logout implements Action {
    readonly type = AuthActionTypes.Logout;
}

export class Register implements Action {
    readonly type = AuthActionTypes.Register;
    constructor(public payload: { authToken: string }) { }
}


export class UserRequested implements Action {
    readonly type = AuthActionTypes.UserRequested;
}

export class UserLoaded implements Action {    
    readonly type = AuthActionTypes.UserLoaded;
    constructor(public payload: { user: User }) { }
}



export type AuthActions = Login | Logout | Register | UserRequested | UserLoaded;
angular angular-material ngrx ngrx-store ngrx-effects
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.