问题描述
在 Angular 中的多个组件和服务之间共享一个常量变量的正确方法是什么?
例如: 考虑一个名为 CountryList 的常量变量,它有一个对象数组,有超过 250 个值键值对。
如何在多个 Angular 组件/服务中共享这个常量值?
const CountryList = [
{name:'UK',value:'United Kingdom'},{name:'USA',value:'United States of America'},{name:'SG',value:'Singapore'},...
]
解决方法
第一种方式(从常量文件导出)
countries.constants.ts
export const CountryList = [
{name:'UK',value:'United Kingdom'},{name:'USA',value:'United States of America'},{name:'SG',value:'Singapore'}
]
test.component.ts
import * as coutriesConstants from '../../shared/constants/countries.constants'
@Component(
...
countries = coutriesConstants.CountryList;
...
第二种方式(创建服务)
countries.service.ts
@Injectable({
providedIn: 'root',})
export class CountriesService {
countryList = [
{name:'UK',value:'Singapore'}
]
}
test.component.ts
@Component(
...
constructor(public countriesSrv: CountriesService){}
// Now you can access the `countriesSrv.countryList` either in the ts file or in HTML
...
第三种方式(注入值)
您也可以像 @jenson-button-event answered 这样注入值。
PS:我通常采用服务方法来避免在我想共享常量数据的每个组件上创建属性,因为这样我的服务将在我需要时通过我的组件注入,这将是一个多一点优化。注入值也有同样的优点,但我发现服务方式更简单,更容易扩展。
,您可以简单地创建一个常量并将其导出。
您可以将 Jhispter 存储库视为示例 (example 1,example 2)。只需在适当的文件夹中创建一个常量并导出即可。
此外,您可以考虑 Angular 如何保持常量 (example 1,example 2)
但是,如果您的常量需要一些复杂的逻辑,请尝试阅读 using of InjectionToken
。
如果你想变得时髦,你可以注射它们..
export const Countries = new InjectionToken('Countries');
@NgModule({
declarations: [
AppComponent
],imports: [
BrowserModule
],providers: [{
provide: Countries,useValue: [
{name:'UK',value:'Singapore'}
]
}],bootstrap: [AppComponent]
})
export class AppModule { }
@Component({
selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(@Inject(Countries) public countries: any[]) { }
}