Angular 使用Ngrx检查Firebase的身份验证状态

Angular 使用Ngrx检查Firebase的身份验证状态,angular,typescript,firebase-authentication,angularfire2,ngrx,Angular,Typescript,Firebase Authentication,Angularfire2,Ngrx,我正在尝试检查我的应用程序的身份验证状态,验证它是否有经过身份验证的用户 我有一个初始状态,其中logged为false,当我尝试签入CanActivate()时,logged将作为false返回 我签入了Redux DevTools,身份验证状态发生了变化,因此记录的值变为true 我做错了什么?如何验证用户是否使用NGRX进行了身份验证 guard.ts constructor( private _store: Store<fromAuth.AuthState> )

我正在尝试检查我的应用程序的身份验证状态,验证它是否有经过身份验证的用户

我有一个初始状态,其中
logged
为false,当我尝试签入
CanActivate()
时,logged将作为false返回

我签入了Redux DevTools,身份验证状态发生了变化,因此记录的值变为true

我做错了什么?如何验证用户是否使用NGRX进行了身份验证

guard.ts

 constructor(
    private _store: Store<fromAuth.AuthState>
  ) { }

 canActivate(): Observable<boolean> {
      return this.checkUserLogged(); // Return is always false 
 }

 private checkUserLogged() {
      return this._store.select(fromAuth.isLogged).pipe(take(1));
 }
    import { Store } from '@ngrx/store';
    import * as fromAuth from '@myapp/store/reducers/auth.reducer';
    import * as authActions from '@myapp/store/actions/auth.actions';

     constructor(
         private _store: Store<fromAuth.AuthState>,
     ) {

    this._store.dispatch(new authActions.GetUser());
 export interface AuthState {
     logged: boolean;
 ;

 export const initialState: AuthState = {
     logged: false,
 };


 export function authReducer(state = initialState, action: Action): 
    AuthState {

switch (action.type) {

    case authActions.GET_USER:
        return {
            ...state,
            logged: false
        };

    case authActions.AUTHENTICATED:
        return {
            ...state,
            ...action.payload,
            loading: false,
            logged: true,
        };

      // emitted ....

 }

 export const getAuthState = createFeatureSelector<AuthState>('auth');

 export const isLogged = createSelector(
     getAuthState, (state: AuthState) => 
     state.logged);
@Injectable({
    providedIn: 'root'
})

export class AuthEffects {

constructor(
    private _actions: Actions,
    private _angularFireAuth: AngularFireAuth) { }

@Effect()
getUser$: Observable<Action> = this._actions.pipe(
    ofType(authActions.GET_USER),
    switchMap(() => this._angularFireAuth.authState),
    switchMap(user => forkJoin([
        from(user.getIdTokenResult(true)), of(user)])
        .pipe(map(([token, user]) => {

            if (user) {
                const authState = {
                    firestoreCollection: token.claims.firestoreCollection,
                    user: {
                        admin: token.claims.admin,
                        uid: user.uid,
                        displayName: user.displayName
                    }
                };

                // You are returning this action
                // Soon after logged in should be true.
                return new authActions.Authenticated(authState);

            } else {
                return new authActions.NotAuthenticated();
            }
        }))),
    catchError((error) => of(new authActions.AuthError(error)))
)
构造函数(
私人商店:商店
) { }
canActivate():可观察的{
返回此值。checkUserLogged();//返回值始终为false
}
私有checkUserLogged(){
返回此。_store.select(from auth.isloged).pipe(take(1));
}
应用程序组件.ts

 constructor(
    private _store: Store<fromAuth.AuthState>
  ) { }

 canActivate(): Observable<boolean> {
      return this.checkUserLogged(); // Return is always false 
 }

 private checkUserLogged() {
      return this._store.select(fromAuth.isLogged).pipe(take(1));
 }
    import { Store } from '@ngrx/store';
    import * as fromAuth from '@myapp/store/reducers/auth.reducer';
    import * as authActions from '@myapp/store/actions/auth.actions';

     constructor(
         private _store: Store<fromAuth.AuthState>,
     ) {

    this._store.dispatch(new authActions.GetUser());
 export interface AuthState {
     logged: boolean;
 ;

 export const initialState: AuthState = {
     logged: false,
 };


 export function authReducer(state = initialState, action: Action): 
    AuthState {

switch (action.type) {

    case authActions.GET_USER:
        return {
            ...state,
            logged: false
        };

    case authActions.AUTHENTICATED:
        return {
            ...state,
            ...action.payload,
            loading: false,
            logged: true,
        };

      // emitted ....

 }

 export const getAuthState = createFeatureSelector<AuthState>('auth');

 export const isLogged = createSelector(
     getAuthState, (state: AuthState) => 
     state.logged);
@Injectable({
    providedIn: 'root'
})

export class AuthEffects {

constructor(
    private _actions: Actions,
    private _angularFireAuth: AngularFireAuth) { }

@Effect()
getUser$: Observable<Action> = this._actions.pipe(
    ofType(authActions.GET_USER),
    switchMap(() => this._angularFireAuth.authState),
    switchMap(user => forkJoin([
        from(user.getIdTokenResult(true)), of(user)])
        .pipe(map(([token, user]) => {

            if (user) {
                const authState = {
                    firestoreCollection: token.claims.firestoreCollection,
                    user: {
                        admin: token.claims.admin,
                        uid: user.uid,
                        displayName: user.displayName
                    }
                };

                // You are returning this action
                // Soon after logged in should be true.
                return new authActions.Authenticated(authState);

            } else {
                return new authActions.NotAuthenticated();
            }
        }))),
    catchError((error) => of(new authActions.AuthError(error)))
)
从'@ngrx/Store'导入{Store};
从“@myapp/store/reducers/auth.reducer”导入*as fromAuth;
从“@myapp/store/actions/auth.actions”导入*作为authActions;
建造师(
私人商店:商店,
) {
此.u store.dispatch(new authActions.GetUser());
auth.reducer.ts

 constructor(
    private _store: Store<fromAuth.AuthState>
  ) { }

 canActivate(): Observable<boolean> {
      return this.checkUserLogged(); // Return is always false 
 }

 private checkUserLogged() {
      return this._store.select(fromAuth.isLogged).pipe(take(1));
 }
    import { Store } from '@ngrx/store';
    import * as fromAuth from '@myapp/store/reducers/auth.reducer';
    import * as authActions from '@myapp/store/actions/auth.actions';

     constructor(
         private _store: Store<fromAuth.AuthState>,
     ) {

    this._store.dispatch(new authActions.GetUser());
 export interface AuthState {
     logged: boolean;
 ;

 export const initialState: AuthState = {
     logged: false,
 };


 export function authReducer(state = initialState, action: Action): 
    AuthState {

switch (action.type) {

    case authActions.GET_USER:
        return {
            ...state,
            logged: false
        };

    case authActions.AUTHENTICATED:
        return {
            ...state,
            ...action.payload,
            loading: false,
            logged: true,
        };

      // emitted ....

 }

 export const getAuthState = createFeatureSelector<AuthState>('auth');

 export const isLogged = createSelector(
     getAuthState, (state: AuthState) => 
     state.logged);
@Injectable({
    providedIn: 'root'
})

export class AuthEffects {

constructor(
    private _actions: Actions,
    private _angularFireAuth: AngularFireAuth) { }

@Effect()
getUser$: Observable<Action> = this._actions.pipe(
    ofType(authActions.GET_USER),
    switchMap(() => this._angularFireAuth.authState),
    switchMap(user => forkJoin([
        from(user.getIdTokenResult(true)), of(user)])
        .pipe(map(([token, user]) => {

            if (user) {
                const authState = {
                    firestoreCollection: token.claims.firestoreCollection,
                    user: {
                        admin: token.claims.admin,
                        uid: user.uid,
                        displayName: user.displayName
                    }
                };

                // You are returning this action
                // Soon after logged in should be true.
                return new authActions.Authenticated(authState);

            } else {
                return new authActions.NotAuthenticated();
            }
        }))),
    catchError((error) => of(new authActions.AuthError(error)))
)
导出接口身份验证状态{
日志:布尔值;
;
导出常量initialState:AuthState={
记录:false,
};
导出函数authReducer(状态=初始状态,操作:操作):
AuthState{
开关(动作类型){
案例authActions.GET\u用户:
返回{
……国家,
记录:错误
};
案例authActions.AUTHENTICATED:
返回{
……国家,
…action.payload,
加载:false,
是的,
};
//发出。。。。
}
导出常量getAuthState=createFeatureSelector('auth');
导出常量isLogged=createSelector(
getAuthState,(状态:AuthState)=>
状态(已记录);
auth.effects.ts

 constructor(
    private _store: Store<fromAuth.AuthState>
  ) { }

 canActivate(): Observable<boolean> {
      return this.checkUserLogged(); // Return is always false 
 }

 private checkUserLogged() {
      return this._store.select(fromAuth.isLogged).pipe(take(1));
 }
    import { Store } from '@ngrx/store';
    import * as fromAuth from '@myapp/store/reducers/auth.reducer';
    import * as authActions from '@myapp/store/actions/auth.actions';

     constructor(
         private _store: Store<fromAuth.AuthState>,
     ) {

    this._store.dispatch(new authActions.GetUser());
 export interface AuthState {
     logged: boolean;
 ;

 export const initialState: AuthState = {
     logged: false,
 };


 export function authReducer(state = initialState, action: Action): 
    AuthState {

switch (action.type) {

    case authActions.GET_USER:
        return {
            ...state,
            logged: false
        };

    case authActions.AUTHENTICATED:
        return {
            ...state,
            ...action.payload,
            loading: false,
            logged: true,
        };

      // emitted ....

 }

 export const getAuthState = createFeatureSelector<AuthState>('auth');

 export const isLogged = createSelector(
     getAuthState, (state: AuthState) => 
     state.logged);
@Injectable({
    providedIn: 'root'
})

export class AuthEffects {

constructor(
    private _actions: Actions,
    private _angularFireAuth: AngularFireAuth) { }

@Effect()
getUser$: Observable<Action> = this._actions.pipe(
    ofType(authActions.GET_USER),
    switchMap(() => this._angularFireAuth.authState),
    switchMap(user => forkJoin([
        from(user.getIdTokenResult(true)), of(user)])
        .pipe(map(([token, user]) => {

            if (user) {
                const authState = {
                    firestoreCollection: token.claims.firestoreCollection,
                    user: {
                        admin: token.claims.admin,
                        uid: user.uid,
                        displayName: user.displayName
                    }
                };

                // You are returning this action
                // Soon after logged in should be true.
                return new authActions.Authenticated(authState);

            } else {
                return new authActions.NotAuthenticated();
            }
        }))),
    catchError((error) => of(new authActions.AuthError(error)))
)
@可注入({
providedIn:'根'
})
导出类AuthEffects{
建造师(
私人行动:行动,
私人{u angularFireAuth:angularFireAuth{}
@效果()
getUser$:Observable=此。\ u actions.pipe(
类型(authActions.GET\u USER),
开关映射(()=>this.\u angularFireAuth.authState),
开关映射(用户=>forkJoin([
from(user.getIdTokenResult(true)),of(user)])
.pipe(映射([令牌,用户])=>{
如果(用户){
常数authState={
firestoreCollection:token.claims.firestoreCollection,
用户:{
管理员:token.claims.admin,
uid:user.uid,
displayName:user.displayName
}
};
//您正在返回此操作
//登录后不久应为真。
返回新的authActions.Authenticated(authState);
}否则{
返回新的authActions.NotAuthenticated();
}
}))),
catchError((error)=>of(new authoctions.authorror(error)))
)

}

由于您已经在reducer中记录了状态,您可以像这样编写index.ts文件从存储中获取数据

从'@core/store/reducers/index'以root格式导入*;
从“./reducers/auth.reducer”导入{AuthState};
从'@ngrx/store'导入{createFeatureSelector,createSelector};
导出接口状态扩展自root.State{
auth:AuthState;
}
导出常量selectAuthState=createFeatureSelector('authModule');
export const selectIsLoginState=createSelector(
选择AuthState,
state=>state.logged
);

基本上,您需要创建选择器来使用createFeatureSelector从存储中获取数据,createSelector

,因为您已经在reducer中记录了状态,您可以像这样写入index.ts文件以从存储中获取数据

从'@core/store/reducers/index'以root格式导入*;
从“./reducers/auth.reducer”导入{AuthState};
从'@ngrx/store'导入{createFeatureSelector,createSelector};
导出接口状态扩展自root.State{
auth:AuthState;
}
导出常量selectAuthState=createFeatureSelector('authModule');
export const selectIsLoginState=createSelector(
选择AuthState,
state=>state.logged
);

基本上,您需要创建选择器来使用createFeatureSelector从存储中获取数据,createSelector

我的回答是否帮助您解决问题?我的回答是否帮助您解决问题?我添加了一个筛选器()来检查加载是否为真,加载是否为真,它不会检查记录是否为真。我添加了一个筛选器()要检查何时加载为真,当加载为真时,它不会检查记录的是否为真。