4
有沒有辦法設置某個應用程序範圍變量/常量可供所有組件使用?如果是,在哪裏聲明它以及如何在組件中引用它?Angular2應用程序範圍變量
我能想到的是
export var SharedValues = {
Title: "aaaaa",
Something: "bbbbb"
}
然後將它導入組件和使用它。
我可以在main.ts中聲明一些東西,然後直接引用它或類似的東西嗎?
有沒有辦法設置某個應用程序範圍變量/常量可供所有組件使用?如果是,在哪裏聲明它以及如何在組件中引用它?Angular2應用程序範圍變量
我能想到的是
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或以前添加到您的引導......
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);
}
}
謝謝,這是@NgModule語法只適用於RC5? – Shawn
是的,我會編輯包含RC4的答案 – jcolemang