简体   繁体   English

导航路线时,Angular 2延迟加载模块多次初始化?

[英]Angular 2 lazy loaded module initializing multiple times when navigating routes?

Using RC5 使用RC5

I have a lazy loaded route configured: 我配置了一个延迟加载的路由:

{path: STATE.PROFILE, loadChildren: 'app/profile/profile.module' },

which points to this module: 指向此模块:

@NgModule({
  imports: [CommonModule, FormsModule, routing],
  declarations: [SelectProfileComponent, ConfirmProfileComponent],
  providers: [ProfileCacheService]
})
export default class ProfileModule { }

... and these routes ...以及这些路线

const routes: Routes = [
  { path: '', component: SelectProfileComponent, canActivate: [ProfileGuard] },
  { path: STATE.CONFIRM, component: ConfirmProfileComponent, canActivate: [ProfileGuard] },
];

In the select-profile component, there is a button to navigate to its sibling route "State.Confirm" via a "shared" service that is declared in root AppModule . 在select-profile组件中,有一个按钮可通过在根AppModule中声明的“共享”服务 导航到其兄弟路由 “ State.Confirm”。 The Angular router facilitates the navigation in this shared service: Angular路由器简化了此共享服务中的导航:

return this.router.navigateByUrl(url);

The problem is that there is state being stored in the ProfileCacheService ( declared in the lazy loaded module ), but is wiped out after I navigate to the "confirm" route. 问题在于,状态存储在ProfileCacheService中( 在延迟加载的模块中声明 ),但是在我导航到“确认”路由后便被清除了。 The reason why this is happening, is because the module is being re-initialized when attempting to navigate to a route within the same lazy-loaded module - which in turns re-initializes the CachService because it is module-scoped 发生这种情况的原因是, 当尝试导航到同一延迟加载的模块内的路由时模块正在重新初始化 -这又由于模块作用域而重新初始化CachService

Declaring the ProfileCacheService on the Root Module solves the issue, but it defeats the purpose of lazy loading, since this service is ever only being used within this module. 在根模块上声明ProfileCacheService可以解决此问题,但是由于仅在此模块中使用了此服务,因此它无法实现延迟加载的目的。

Has anyone ran into the same issue? 有没有人遇到过同样的问题?

I've had the same problem, it looks like it has been fixed in master and will be part of rc6: 我遇到了同样的问题,看起来它已经在master中修复,将成为rc6的一部分:

https://github.com/angular/angular/issues/10841 https://github.com/angular/angular/issues/10841

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM