Angular:如何在模块中声明变量并从所有组件访问它?

Elb*_*baz 6 angular

我想在我的 app.module 中声明变量并从子组件访问它,
而无需再次声明或使用全局注入。

这可能吗?

Pen*_*gyy 5

您可以定义 aString Token并通过Injectorfrom将其注入到您的组件中@angular/core

应用模块.ts

const testVar = 'some value';
@NgModule({
  ...
  providers: [
    { provide: 'A', useValue: testVar}   // define a string token
  ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

成分

import { Injector } from '@angular/core';

constructor(private injector: Injector) {
  const A = this.injector.get('A');
  console.log(A);
}
Run Code Online (Sandbox Code Playgroud)

演示