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

时间:2018-11-13 13:44:23

标签: angular typescript authentication jwt local-storage

编辑:我用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' }];

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);
       }

}

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');
  }
}

1 个答案:

答案 0 :(得分:3)

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);
    })
  );
}

并对此进行更新:

if (id) {
  this.router.navigate(["/courses"]);
  return this.authUserService.login(id);
}