为什么Angular会调用我的函数......几十次?

时间:2018-05-21 20:53:21

标签: angular

我的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

enter image description here

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

0 个答案:

没有答案