【问题标题】:angular component loading before app.componentapp.component 之前的角度组件加载
【发布时间】:2019-11-21 18:18:57
【问题描述】:

我在应用程序组件中注入 userService 是因为我不希望我的服务在我的应用程序的每个组件中注入它时为空。 所以,我想要发生的是使用登录用户加载 app.component,然后加载我的组件。 实际发生的是组件在 app.component 之前加载,而我的用户未定义。

如何让app组件先加载?

另外,我有 app.module 和 2 个其他模块 core.module 和 shared.module

export class AppComponent implements OnInit {

  @HostListener("window:beforeunload",["$event"])
  loading = true;

  constructor(public  router: Router,
              public  userService: UserService,
              private accountService: AccountService,
              private toastr: ToastrService
  ) { }

  ngOnInit() {
    StorageHelper.getToken()
      ? this.getUserDetails()
      : this.loading = false;
  }

  getUserDetails() {
    this.accountService.getUserDetails().subscribe(res => {
      this.userService.setCurrentUser(<User>res);
      this.loading = false;
    }, error => {
      StorageHelper.killSession();
      this.toastr.error('login error');
      this.loading = false;
      this.router.navigate([Urls.LOGIN]);
    });
  }

组件 => getCurrentUser() -> null

export class MyComponent implements OnInit {
constructor(private userService: UserService,
private myService: MyService) {}

ngOnInit() {
this.getPolicies();
}

getPolicies() {
this.myService.getPolicies(this.userService.getCurrentUser().id).subscribe(res => {
....
})
)

【问题讨论】:

    标签: angular


    【解决方案1】:

    您的问题不在于实例化 userService 时。这是您首次访问用户详细信息的方式。

    因为 this.accountService.getUserDetails() 是一个 observable,即使 userService 被实例化了你的 this.userService.setCurrentUser(res);将被称为后者。

    要解决此问题,您可以使用各种方法: -只有在 this.accountService.getUserDetails() 完成后,你才能使用 routerguard 并加载组件

    文档:https://angular.io/api/router/CanActivate

    例如:

    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(private accountService: AccountService,
                  private userService: UserService,
                  private router: Router) {
      }
    
      canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>  {
        return this.accountService.getUserDetails().pipe(map(res => {
          this.userService.setCurrentUser(res);
          return true;
        }), catchError(() => {
          this.router.navigate(['/login']);
          return of(false);
        }));
      }
    }
    

    【讨论】:

      【解决方案2】:

      我建议你看看预取组件数据:

      https://angular.io/guide/router#resolve-pre-fetching-component-data

      就像上面评论中所说的那样-您的问题不在于在 App 之前加载服务。但是,如果您想在渲染任何其他组件之前解析数据 - 预取将帮助您。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-07
        • 1970-01-01
        • 2020-12-10
        • 2017-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        相关资源
        最近更新 更多