简体   繁体   English

Angular - 如何重用标准数据数组

[英]Angular - how to reuse a standard data array

I am using a Indian states data array like the below in various components of my Angular project.我在我的 Angular 项目的各个组件中使用如下印度州数据数组。

I know one way is to add it as a collection in backend database.我知道一种方法是将其作为集合添加到后端数据库中。 But I would not like to make an API call to get the state names every time a dropdown needs it.但我不想每次下拉需要时都调用 API 来获取 state 名称。

What is the best way to define it in ONE place within angular instead of defining this constant separately in each component.在 angular 的一个地方定义它的最佳方法是什么,而不是在每个组件中单独定义这个常量。

const States = [
 { name:"Assam",  code:"18",  tin:"AS" },
  { name:"Bihar",  code:"10",  tin:"BH" },
  { name:"Chandigarh",  code:"04",  tin:"CH" },
....
]

I guess that the best practice would be to create a service - eg StatesService that would be provided either in a module or a root of the application depending on the needs.我想最好的做法是创建一个服务——例如,根据需要在模块或应用程序的根目录中提供的 StatesService。 I would add a getStates() method that would return observable of the states.我将添加一个 getStates() 方法,该方法将返回可观察到的状态。

This way, in case your architecture ever changes, you're prepared that your data CAN be returned asynchronously from external source and all your code would still be valid.这样,如果您的架构发生变化,您就可以准备好从外部源异步返回您的数据,并且您的所有代码仍然有效。

A sample implementation:示例实现:

export class State {
  name: string;
  code: string;
  tin: string;
}

@Injectable({
  providedIn: 'root',
})
export class StatesService {
    private states: State[] = [
    { name:"Assam",  code:"18",  tin:"AS" },
     { name:"Bihar",  code:"10",  tin:"BH" },
     { name:"Chandigarh",  code:"04",  tin:"CH" },
   ];

   getStates(): Observable<State[]> {
     return of(this.states);
   }
}

You could create a file, constArrays.ts somewhere near the root of your application.您可以在应用程序根附近的某个位置创建一个文件constArrays.ts You can then export the constant value like so:然后,您可以像这样export常量值:

// constArrays.ts

export const States = [
 { name:"Assam",  code:"18",  tin:"AS" },
  { name:"Bihar",  code:"10",  tin:"BH" },
  { name:"Chandigarh",  code:"04",  tin:"CH" },
....
]

You can then import and use this in any other file like this:然后,您可以在任何其他文件中导入并使用它,如下所示:

import * as constArrays from 'path/to/file/constArrays';
let states = constArrays.States;

I think it is very easy to use and maintain with a configuration file.我认为使用配置文件非常容易使用和维护。

states.config.json states.config.json

[
  { "name":"Assam",  "code":"18",  "tin":"AS" },
  { "name":"Bihar",  "code":"10",  "tin":"BH" },
  { "name":"Chandigarh",  "code":"04",  "tin":"CH" }
]

then import it when need然后在需要时导入

import states from 'src/assets/states.config.json';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM