I have an app with 2 main modules, web and admin.

Admin declares

  providers: [
    {
      provide: DISPLAY_LIFE_TOKEN,
      useValue: 6000,
    },
  ],

and web declares the same token with useValue: 10000.

Both modules contain a route and components that use a service with providedIn: 'root', that imports the token DISPLAY_LIFE_TOKEN.

Yet in the service, the config value is always 10000 even when calls come from the admin module.

See demo.

Did i misunderstand something about injectionTokens and providers, or is there another preferred way to set a module wide config?

推荐答案

Services are singleton in Angular.

The only way around this is lazy loading. This ensures a separate instance is created for services provided in the lazy module.

Remove providedIn: 'root', from the service. Add the service to both module providers array.

  providers: [
    MessageService,
    {
      provide: DISPLAY_LIFE_TOKEN,
      useValue: 6000,
    },
  ],

And update the router module to use lazy loading:

   {
      path: 'admin',
      loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
    },
    {
      path: 'web',
      loadChildren: () => import('./web/web.module').then(m => m.WebModule),
    }]

(since this moves the path from admin module to app module, do not forget to also update the route in the admin module).

Demo

Angular相关问答推荐

Angular 5 国际化

如何使用 Bootstrap 4 flexbox 填充可用内容?

CORS 错误:“requests are only supported for protocol schemes: http…”等

如何在 Angular 2 中创建可重用的动画

在Angular2 Dart中设置路由和RouterLink的正确方法是什么

如何防止角material垫菜单关闭?

无法绑定到“ target”,因为它不是“div”的已知属性

如何在Angular 2 中为异步验证器添加debounce 时间?

在Angular 2+中生成没有spec.ts文件的组件

如何将 Angular CLI 升级到最新版本

angular-cli 服务器 - 如何将 API 请求代理到另一台服务器?

如何在 Angular2 中订阅服务上的事件?

Angular 2 应该使用哪种类型的文件夹 struct ?

Angular 教程中的 pipe 和 tap 方法是什么?

禁用控件不包含在 form.value 中

如何获得 Angular 版本?

CUSTOM_ELEMENTS_SCHEMA 添加到 NgModule.schemas 仍然显示错误

有没有办法从 Angular 2+ 中删除未使用的导入(imports)和声明(declarations)?

Angular异常:无法绑定到“ngForIn”,因为它不是已知的本机属性

如何使用“*ngIf else”?