问题描述
我最近迁移到了 Angular 2 RC 5 并将我应用中的子模块转换为 NgModule.
I've recently migrated to Angular 2 RC 5 and converted the sub-modules in my app to NgModule.
鉴于 plunker 在 plunker="https://angular.io/docs/ts/latest/guide/router.html" rel="nofollow">Angular2 路由文档,如何将 CrisisCenterModule 中的 CrisisService 变成一个 stateful singleton在危机中心模块的路线中共享.
Given the following plunker provided in the Angular2 Routing Documentation, how can the CrisisService in the CrisisCenterModule be turned into a stateful singleton that is share across the routes of the crisis-center module.
当前为模块中的每个路由实例化了一个新的 CrisisService.
Currently a new CrisisService is instantiated for every route in the module.
例如如果您在 CrisisService 中添加一个简单的构造函数,如下所示:
e.g. if you add a simple constructor in the CrisisService, like so:
constructor() {
console.log("Hello from CrisisService");
}
每次链接到不同的子路由时,浏览器控制台都会注销该字符串,例如/crisis-center 或/crisis-center/11
The browser console will log out that string every time you link to a different sub-route, e.g. /crisis-center or /crisis-center/11
我希望能够通过一个服务在模块中的组件之间共享状态,该服务在您离开该模块时被清除,而无需将该服务移动到全局共享模型中.
I'd like to be able to share state across the components in a module via a service that is cleared whenever you route away from this module, without moving the service into a global shared model.
谢谢
推荐答案
Edited answer 2016 Dec 05 at 11:14:
Edited answer 2016 Dec 05 at 11:14:
该问题是一个错误,已在 https://github.com/angular/中修复角度/问题/11125.
The problem was a bug and was fixed in https://github.com/angular/angular/issues/11125.
所以,现在您可以在任何模块中加载服务,而不仅仅是在应用程序中,而且您将拥有它的孩子的单例.
So, now you can load the service at any module, not only in the app, and you will have a singleton for it's children.
旧答案 - 2016 年 8 月 22 日 20:20:
Old answer - 2016 Aug 22 at 20:20:
我找到了在 RootModule (AppModule) 而不是在子模块 (CrisisCenterModule) 中提供服务的解决方案.
I found a solution providing the service in the RootModule (AppModule) and not in the Submodule (CrisisCenterModule).
我现在知道这是错误还是正确的行为.
I do now know if it is a bug or if it is the right behaviour.
如果您找到任何关于此的文档,请告诉我,否则我将在 Angular2 github 存储库中打开一个问题.
If you find any documentation about this, please, let me know or I'll open an issue in the Angular2 github repo.
这篇关于angular2 rc5 路由器服务单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!