1

我有一个了解可注入服务的“Services.Module”设置。它被加载到“imports”下的“app.module”中。一切正常,应用程序运行良好,可以调用多个服务上的端点。但是,在授权服务上,我有一个类似于:

@Injectable()
export class AuthService {
    private endpoint = `${environment.baseApi}/auth`;
    private headers: HttpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
    //Can set this to a regular instance variable and same problem occurs
    public static jwt: JWT;

    constructor(private http: HttpClient) { }

    public createAuthToken(user: UserModel): Observable<JWT> {
        return this.http.post<JWT>(`${this.endpoint}/createUserToken`, user, { headers: this.headers})
    }

    get getJWT() {
        return AuthService.jwt;
    }
}

我用一个登录组件来调用它,比如:

 .subscribe((str: string) => {
       ...
        var u = ...
        this.authService.createAuthToken(u)
          .subscribe((jwt: JWT) =>  
          {
            //works just fine
            AuthService.jwt = jwt;
            this.router.navigate(['/Category']);
          })

为这样的路由设置了路由保护:

path: 'Category',
canActivate: [LoginGuard],
component: CategoryComponent

守卫被击中,世界一切正常,如下图所示:

@Injectable()
export class LoginGuard implements CanActivate, CanLoad {
  constructor(private authService: AuthService,
    private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
      return this.checkLoggedIn(state.url);
  }

  canLoad(route: Route): boolean {
      return this.checkLoggedIn(route.path);
  }

  checkLoggedIn(url: string): boolean {
      console.log(`jwt is: ${this.authService.getJWT}`);
      if(this.authService.getJWT != null) {
          return true;
      }
      console.log("Must be logged in first");
      this.router.navigate(['/login']);
      return false;
  }
}

问题是,如果我在浏览器上,然后手动执行(根)/类别,则 AuthService 上的“jwt”静态变量设置为未定义。 如果我想保留一个变量,我可以设置和重置 GLOBALLY 和 REFERENCE IT 而不会变成为守卫重置的实例,Angular 6 中的最佳实践是什么? 我基本上只想去'token you now are blahblahblah',直到我刷新浏览器或重新启动应用程序,我希望你的状态保持不变。

4

0 回答 0