有没有办法设置某些应用程序范围的变量/常量,供所有组件使用?如果是,在哪里声明它以及如何在组件中引用它?
我能想到的是
export var SharedValues = {
Title: "aaaaa",
Something: "bbbbb"
}
然后在组件中导入并使用它。
我可以在 main.ts 中声明一些东西然后直接引用它或类似的东西吗?
最佳答案
您可以将其打包到一个类中并将其用作服务。例如,
@Injectable()
export class SharedValues {
public Title = 'aaaaa';
public Something = 'bbbbb';
}
然后,如果您在模块中使用 RC5 包含...
import { SharedValues } from 'some/path/shared-values.service';
@NgModule({
// declarations, imports, bootstrap...
providers: [
// your other providers
SharedValues,
]
}) export class AppModule {}
如果您使用的是 RC4 或以前的版本,请添加到您的 Bootstrap 中...
import { SharedValues } from 'some/path/shared-values.service';
bootstrap(AppComponent, [
// ...
SharedValues,
]);
无论你想在哪里使用它...
import { SharedValues } from 'some/path/shared-values.service';
// or wherever you want to use the variables
@Component({
// ...
}) export class SomeComponent {
constructor(private shared: SharedValues) {
console.log(this.shared.Title, this.shared.Something);
}
}
关于typescript - Angular2 应用范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38641823/