微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular AuthGuard - NgRx - 重新加载重定向通用

如何解决Angular AuthGuard - NgRx - 重新加载重定向通用

问题出在 Angular Universal,如果我在没有 Universal 的情况下构建应用程序它工作正常,但使用 Angular Universal 这就是问题所在。

我在 ngrx 和 Angular Universal 中使用 angular,在每次重新加载时,我都会向后端发送请求,然后检索用户数据。如果路由在重新加载时受到身份验证保护保护,如果用户首先登录,它会重定向到 /login,然后在 0.5 秒后重定向到受保护的路由,数据已加载,一切正常,但为什么它首先显示 /login ?

授权保护

  canActivate(
    route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

      return this.store.select(fromAuth.selectAuthState).pipe(
        map(authState => authState.isInitializing),filter((isInit) => !isInit),tap((data) => console.log(data)),switchMap(() => {
          return this.store.select(fromAuth.selectAuthState).pipe(
            map(authState => authState),map((isAuth) => {
              console.log(isAuth);
              if (isAuth.user) return true;
              return this.router.createUrlTree(['/login'],{ queryParams: { returnUrl: state.url } });
            }),take(1)
            );
        })
      );

Ngrx/store 中的初始状态

export const initialState: State = {
  isAuthenticated: false,isInitializing: true

登录成功和登录失败 isInitializing 设置为 false

  on(AuthActions.logInSuccess,(state) => {
    return {
      isInitializing: false,isAuthenticated: true,};
  }),

我正在 APP_INITIALIZER 中调度 isLoggedIn 操作

export function appInitializerFactory(
  store: Store<any>
) {
  return () => {
          store.dispatch(AuthActions.isLoggedIn());
  };
}

  providers: [
    {
      provide: APP_INITIALIZER,useFactory: appInitializerFactory,deps: [Store],multi: true
  }
  ]

内部验证效果

  isLoggedIn$ = createEffect(() =>
    this.actions$.pipe(
      ofType(AuthActions.isLoggedIn),switchMap(() => {
        return this.authService.isLoggedIn().pipe(
          switchMap((user: any) => {
            return [
              AuthActions.logInSuccess({ token: user.token,name: user.data.user.name,email: user.data.user.email,id: user.data.user._id,likedProperties: [...user.data.user.likedPropertiesSell,...user.data.user.likedPropertiesRent],myProfileinformations: userProfile })]
          }),catchError(err => {
            return of(AuthActions.logInFail({ error: `code ${err.status}` }))
          }
          )
        );
      })
    )
  );

来自 Auth Guard 的控制台日志

2020-12-24T14:01:53.070535+00:00 app[web.1]:   isAuthenticated: false,2020-12-24T14:01:53.070535+00:00 app[web.1]:   user: null,2020-12-24T14:01:53.070536+00:00 app[web.1]:   errorMessage: 'code undefined',2020-12-24T14:01:53.070537+00:00 app[web.1]:   likedProperties: null,2020-12-24T14:01:53.070537+00:00 app[web.1]:   following: null,2020-12-24T14:01:53.070538+00:00 app[web.1]:   followingListLoaded: false,2020-12-24T14:01:53.070538+00:00 app[web.1]:   myProfileinformations: null,2020-12-24T14:01:53.070539+00:00 app[web.1]:   isInitializing: false
2020-12-24T14:01:53.070539+00:00 app[web.1]: }

所以 store 在检索用户数据之前将 isInitializing 设置为 false,我真的不知道为什么 errorMessage 存在那里,在 redux store logInFail() 永远不会被调度

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?