Angular 6:刷新后从 localStorage 获取令牌

Ofi*_*son 1 authentication local-storage jwt typescript angular

编辑:我用 PierreDuc 给我的答案更新了代码。他的解决方案对我有用。我编辑代码以便每个人都可以看到工作代码

我正在使用 canActivate 和 canActivateChild 来了解是否有人拥有我的网络令牌,我想阻止任何没有令牌的人。我将 localStorage 用于用户数据和令牌。

当我尝试使用用户 id:1 登录时,守卫导航到未找到的页面,但在我刷新页面后,我可以访问该页面。当我使用调试器时,我看到在刷新之前 localStorage 是空的,但在刷新后有值。

为什么会发生这种情况?我该如何解决?这是相关代码:

app-routing.module.ts

const appRoutes: Routes = [
  { path: 'login/:id', canActivate: [AuthGuard], children: [] },
  { path: '', canActivateChild: [AuthGuard], children: [
    { path: '', redirectTo: '/courses', pathMatch: 'full' },
    { path: 'courses', component: CourseListComponent,  pathMatch: 'full'},
    { path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' },
    { path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent,
      children: [
        { path: '', component: CourseListComponent },
        { path: 'lesson/:lessonId', component: CourseLessonComponent, data:{ type: 'lesson'} },
        { path: 'quiz/:quizId', component: CourseQuizComponent, data: {type: 'quiz'} }
      ]}
    ]},
  { path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];
Run Code Online (Sandbox Code Playgroud)

auth.guard.ts

export class AuthGuard implements CanActivate , CanActivateChild {

    constructor(private authUserService: AuthUserService, private router: Router) {   }

    canActivate(route: ActivatedRouteSnapshot, state:
    RouterStateSnapshot): boolean |
    Observable<boolean> | Promise<boolean> {
      // save the id from route snapshot
      const id = +route.params.id;

      // if you try to logging with id
      if (id) {
        this.router.navigate(["/courses"]);
        return this.authUserService.login(id);
      }

      // if you already logged and just navigate between pages
      else if (this.authUserService.isLoggedIn())
         return true;

      else {
        this.router.navigate(["/page_not_found"]);
        return false;
      }
     }

      canActivateChild(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
         return this.canActivate(route, state);
       }

}
Run Code Online (Sandbox Code Playgroud)

auth-user.service.ts

import { Injectable, OnDestroy } from '@angular/core';
import { Observable , BehaviorSubject } from 'rxjs';
import { LocalStorage } from '@ngx-pwa/local-storage';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { catchError, groupBy } from 'rxjs/operators';

import { UserService } from './user.service';
import { IUser } from './user';

@Injectable()
export class AuthUserService implements OnDestroy {

  private user: IUser;
  private errorMessage: string;

  constructor(private userService: UserService) { }

  // store the session and call http get
  login(id: number) {
    return this.userService.getUser(id).pipe(
      map((user) => {
        this.user = user;
        localStorage.setItem('user', JSON.stringify(this.user));
        localStorage.setItem('token', 'JWT');
        return true;
      }),
      catchError((error) => {
        this.errorMessage = <any>error;
        return of(false);
      })
    );
  }

  isLoggedIn() {
   return !!localStorage.getItem('token');
  }

  ngOnDestroy() {
    localStorage.removeItem('user');
    localStorage.removeItem('token');
  }
}
Run Code Online (Sandbox Code Playgroud)

Pie*_*Duc 5

userService.getUser是异步的,它不会完成,并且会在您检查完之后设置您的 localStorage。

将您的 authService 更改为:

login(id: number) {
  return this.userService.getUser(id).pipe(
    map((user) => {
      this.user = user;
      localStorage.setItem('user', JSON.stringify(this.user));
      localStorage.setItem('token', 'JWT');
      return true;
    }),
    catchError((error) => {
      this.errorMessage = <any>error;
      return of(false);
    })
  );
}
Run Code Online (Sandbox Code Playgroud)

并将您的守卫更新为:

if (id) {
  this.router.navigate(["/courses"]);
  return this.authUserService.login(id);
}
Run Code Online (Sandbox Code Playgroud)