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路由不响应子路由的子路由

向Anguar 17项目添加服务以启动和停止Loader-NGX-UI-Loader

Angular 16模块中未使用的组件是否从Bundle 包中删除(树摇动)?

如何在Angular功能路由保护中取消订阅RxJs主题

一次重定向后,所有子路由都处于活动状态

等待可观察性完成后再调用下一个

除非将 signal.set 作为间隔的一部分调用,否则Angular 信号效果不会执行

Angular 升级后 RXJS SwitchMap 无法与解析器一起正常工作

在 kubernetes 上创建 Ingress 服务以将 springboot [后端] 连接到前端 [angular]

最新版本的 Chrome ERR_TIMED_OUT

在一个组件中创建多个表单

单选按钮的Angular2 Reactive Forms formControl

如何在 Angular4 中访问组件的 nativeElement?

将 Angular 5 升级到 6 时,我得到不兼容的对等依赖(使用 ng update @angular/core)

Angular 2 应用程序中没有Access-Control-Allow-Origin标头

Angular 中 polyfills.ts 文件有什么用

Angular 2 filter/search 列表

angular2 测试,我如何模拟子组件

如何升级 Angular CLI 项目?

在 Angular 2 中对 observable 进行单元测试