【问题标题】:Not able to access JSON data into angular(.ts) file无法将 JSON 数据访问到 angular(.ts) 文件中
【发布时间】:2018-03-06 07:16:25
【问题描述】:

我正在尝试使用 ngx-translate 为我的 Web 应用程序实现国际化。我能够访问 HTMl 文件中的 JSON 数据,但无法访问 angular(.ts) 文件中的 JSON 数据。谁能建议我如何在 .ts 文件中访问它。

【问题讨论】:

    标签: json angular typescript localization internationalization


    【解决方案1】:

    您从 json 文件中获取输入,就像调用后端服务一样。语法是一样的,但是如果你从本地 json 文件中读取,它是一个同步调用。

    // Import HTTP Client
    import { HttpClient } from '@angular/common/http'; 
    
    // Define property
    myDataObject: any;
    
    // Dependency Injection
    constructor(private http: HttpClient) {}
    
    // Get the data
    ngOnInit() {   
      this.myDataObject = this.http.get<any>("assets/json/data.json")
        .map(response => response)
    }
    

    现在您可以从 json 对象中获取属性,例如:

    this.myDataObject.myProperty
    

    【讨论】:

      猜你喜欢
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 2019-08-21
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      相关资源
      最近更新 更多