angular 读取json文件

步骤简介

1. 把json文件放入 angular 项目目录的 assets 文件夹下(这样就可直接读取)

2. 导入angular中的 HttpClientModule 来读取,这样就可在组件的代码中调用hrrpClient类的get()方法,把json转为observable读取

 

以下是例子

1. json 文件:

{
    "test_type": "command",
    "button_name": "ResetTable",
    "mock_api": {
      "method": "POST",
      "path": "/api/v1/CT/utility/table/reset",
      "response_body": {}
    },
    "command": {
      "property_names": ["TableController"],
      "command_name": "ResetTableCommand",
      "command_body": {
        "mode": 0 
      }
    }
  }
  

2. 

constructor(
    private httpClient: HttpClient
) {}

  public getSingleFile(testCaseUrl: string): Observable {
    return this.httpClient.get(testCaseUrl);
  }

// testCaseUrl 是json文件的路径, 如: assets/test.json

commandMethod(commandName: string) {
    let testCaseUrl = `assets/machineAPI/command/${commandName}.json`;
    console.log(commandName);
    this.getSingleFile(testCaseUrl)
      .pipe(takeUntil(this.destory$))
      .subscribe(data => 
{cosnt x = date['command']['property_names'];
console.log(x)})
}

//打印出的x为 ["TableController"]

// 这里好像不需要取消订阅, 因为是使用了httpClient, 待定

 

你可能感兴趣的:(angular)