我的AuthService
用于身份验证;用户登录后,user
属性返回User
实例(注意console.log
):
@Injectable()
export class AuthService {
// ...
get user(): null | User {
console.log('Calling getUser()');
const decodedToken: { sub: {} } | null = this.jwtHelper.decodeToken(this.authToken);
if (!decodedToken) {
return null;
}
return plainToClass(User, decodedToken.sub);
}
}
我基本上只在authService.user
打了一次header-component.html
:
<!--- ... --->
<a class="nav-link" [routerLink]="['logout']">Logout ({{ authService.user.username }})</a>
问题:当我刷新页面时,JavaScript控制台会显示数十次调用getUser()。这怎么可能?谁多次致电authService.user
?
AuthService
参考1 :app.modules.ts
JwtModule.forRoot({
jwtOptionsProvider: {
provide: JWT_OPTIONS,
useFactory: (authService: AuthService) => {
return { tokenGetter: () => authService.authToken };
},
deps: [AuthService]
}
}),
AuthService
参考2 :在core.module.ts
作为提供者:
providers: [
// ...
AuthService
],
AuthService
参考3 :注入HeaderComponent
:
export class HeaderComponent implements OnInit {
constructor(readonly authService: AuthService) { }
}
AuthService
参考4 :注入LoginComponent
:
export class LoginComponent implements OnInit {
constructor(private authService: AuthService) { }
AuthService
参考5 :注入LogoutComponent
:
export class LogoutComponent implements OnInit {
constructor(private authService: AuthService) { }
}