0

这是我在 app.module.ts 文件中路由的角度代码。

const appRoutes: Routes = [
{path: '', component: LoginformComponent},
  {path: 'dashboard', component: DashboardComponent, canActivate: [AuthenticationGuard]},
  {path: 'user', children: [
      {path: '', component: UserComponent},
      {path: ':id', component: UserdetailComponent}
    ], canActivate: [AuthenticationGuard]
  },
  {path: '**', component: NotfoundComponent}
];

以下代码代表保护文件。

export class AuthenticationGuard implements CanActivate {

  constructor(private user: UserService, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (! this.user.getUserLoggedIn()) {
      this.router.navigate(['/']);
    }
    return this.user.getUserLoggedIn();
  }
}

当我以用户身份登录时,Guard 工作正常。但如果刷新它,我会退出。我想要一种方法让我在刷新页面后也能保持登录系统?

这是用户 service.ts 文件,

@Injectable()
export class UserService {
  private isUserLoggedIn: boolean;
  private username: string;

  constructor() {
    this.isUserLoggedIn = false;
  }

  setUserLoggedIn(username) {
    this.isUserLoggedIn = true;
    this.username = username;
  }

  getUserLoggedIn() {
    return this.isUserLoggedIn;
  }

  getUserName() {
    return this.username;
  }
}

有人能帮我吗..........

4

1 回答 1

3

当您刷新页面时,整个应用程序将再次加载,即组件再次经历其生命周期。根据应用程序的体系结构,您需要保存身份验证信息,以便在页面刷新之间保持不变。

在工作 Angular 时最常使用 JWT,但并非总是如此。如果您使用 JWT,则应将 JWT 令牌保存在 cookie 中,并在应用重新加载时检查它是否存在。如果退出,则从 cookie 中读取并正常继续,否则要求用户再次登录。

于 2017-09-20T03:11:44.053 回答