带解析器的Angular 7路线不会加载组件

时间:2018-12-02 02:53:32

标签: angular rxjs angular7

我遇到了一个Angular 7问题,该路由中具有解析器的模块的子组件无法加载。

app-routing.module.ts

with open('compare_out.txt', 'w', encoding='utf-8') as fout:
    for values in text_dict.values():
        fout.write(str(values))

account-routing.module.ts

{
  path: 'Account',
  loadChildren: './account/account.module#AccountModule'
}

profile.resolver.ts

{
  path: 'Profile',
  component: ProfileComponent,
  resolve: {
    profile: ProfileResolver
  }
}

profile.component.ts

@Injectable()
export class ProfileResolver implements Resolve<Profile> {

  constructor(private readonly accountService: AccountService) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Profile> {
    return this.accountService.profile();
  }
}

account.service.ts

@Component({
⋮
})
export class ProfileComponent implements OnInit {

  model: Profile;

  constructor(private readonly route: ActivatedRoute) {
  }

  ngOnInit(): void {
    this.model = this.route.snapshot.data['profile'] as Profile;
  }
}

行为是,导航到@Injectable() export class AccountService { constructor(protected readonly http: HttpClient) { } profile(): Observable<Profile> { return this.http.get<Profile>(`${environment.apiUrl}/Account/Profile`); } } 时,将调用/Account/Profile,命中服务器,并通过ProfileResolver对象获得200响应(我可以在网络标签),然后什么都没有。不会调用Profile的{​​{1}}或constructor方法。

如果我从ngOnInit中删除了ProfileComponent,并直接从ProfileResolver方法中调用了AccountRoutingModule,它将起作用。但是,模板在等待响应时会出现很多模板解析错误(这就是我要使用AccountService的全部原因)。

要使解析器与这些模块一起工作,我还需要做些其他事情吗?

这也可能是此处所述的相同问题:Angular Router don't load component with resolver

更新:我打开了ngOnInit,以便可以看到发生了什么。输出如下:

resolve

因此,看来enableTracing事件从未触发。我发现了这个问题:Router's ActivatedRoute data returns empty {} if module is lazy。看来这可能是相关的,但我不确定如何在此处实施该修补程序。

2 个答案:

答案 0 :(得分:2)

我认为您必须订阅解析器承诺

@Component({
⋮
})
export class ProfileComponent implements OnInit {

  model: Profile;

  constructor(private readonly route: ActivatedRoute) {
  }

  ngOnInit(): void {

    this.router.data.subscribe( (data) => { <== here 
      this.model = data as Profile  <== here
    });
  }
}

答案 1 :(得分:1)

我再次查阅了Routing & Navigation指南,并更改了我的解析器,使其看起来像在这里一样:

profile.resolver.ts

@Injectable()
export class ProfileResolver implements Resolve<Profile> {

  constructor(private readonly accountService: AccountService) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Profile> {
    return this.accountService.profile().pipe(
      take(1),
      map((profile: Profile) => profile));
  }
}

键正在添加take(1)。没有这个,ResolveEnd事件就永远不会触发,Router只会挂起。