懒加载模块的Angular onSameUrlNavigation

时间:2019-09-11 13:31:36

标签: javascript angular rxjs lazy-loading angular-routing

我对延迟加载的模块数据重新获取有问题。 onSameUrlNavigation根本不起作用

我为延迟加载的功能提供了单独的路由模块,也许我无法正确集成onSameUrlNavigation

项目结构:

app/
    app.component.ts
    app.module.ts
    app-routing.module.ts
        someFeature/
            someFeature.module.ts
            someFeature-routes.module.ts
            someFeature.component.ts

应用路由模块代码:

    export const routes: Routes = [{
      {
      path: 'myfeature',
      loadChildren: () => import('./someFeature/someFeature.module').then(m => m.someFeatureModule),
      canActivate: [AuthGuard],
      runGuardsAndResolvers: 'always',
    }}]

@NgModule({
  imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
  exports: [RouterModule],
})
export class AppRoutingModule {
}

延迟加载的路由模块:

    const routes: Routes = [
      {
        path: '',
        component: someFeatureComponent,
      },
    ];
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule],
    })

组件代码:

    ngOnInit(): void {
    this.unsubscribe$ = new Subject<void>();
    this.route
      .queryParams.pipe(
      takeUntil(this.unsubscribe$),
      map(p => {
        this.loading = true;
        if (p.page && p.limit) {
          this.page = p.page;
          this.limit = p.limit;
        }
        return {
          page: this.page,
          limit: this.limit,
        };
      }),
      flatMap((f) => this.myService.getData(f)),
      tap(() => this.loading = false),
    )
      .subscribe((payload) => {
        this.data = payload.data;
      })
    ;
  }

这是有问题的部分(在组件代码中)

 reload(): void {
    this.router.navigate(['someFeature'], {queryParams: {page: this.page, limit: this.limit}});
  }
refetchDataOnClick(){
 this.reload();
}

数据是在第一个请求上获取的(因此,我认为模块导入或类似的操作没有问题),但是重新获取没有发生,因为我看到API上没有其他请求。

我尝试添加和删除“ runGuardsAndResolvers” someFeature-routes模块,但没有成功。 我还尝试将onSameUrlNavigation添加到someFeature-routes模块中,但是forChild只能接受一个参数

1 个答案:

答案 0 :(得分:0)

由于用户fridoo的评论,我找到了解决方法

我没有调用重新加载组件的方法,而是重新加载了数据

this.loading = true;
    this.myService.getData({page: this.page, limit: this.limit})
      .pipe(
        takeUntil(this.unsubscribe$),
        finalize(() => this.loading = false))
      .subscribe((payload) => {
        this.data = payload.data;
      });