如何将本地 JSON 读入 Angular 打字稿文件

How to read a local JSON into Angular typescript file

我正在使用 primeng Datepicker。 [locale] 属性 接受我存储在名为 datePickerLanguages.json:

的本地 json 中的语言
{
    "DatePickerLanguages": [{
            "spanish": {
                "firstDayOfWeek": 1,
                "dayNames": ["domingo", "lunes", ...],
                "dayNamesShort": ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
                "dayNamesMin": ["D", "L", "M", "X", "J", "V", "S"],
                "monthNames": [
                    "Enero",
                    "Febrero",
                    ...
                    "Diciembre"
                ],
                "today": "Hoy",
                "clear": "Borrar"
            }
        },

        {
            "german": {
                "firstDayOfWeek": 1,
                "dayNames": ["Sonntag", "Montag",...]
                ...
                "today": "Heute",
                "clear": "Klar"
            }
        }
    ]
}

我必须将 spanishgerman 或任何其他语言(一次一种语言)传递到 p-calendar[locale]=xxxxx 中。我的打字稿是:

import { Component, OnInit, VERSION } from "@angular/core";
import languages from "./datePickerLanguages.json";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  name = "Angular " + VERSION.major;

  value;

  languageList: {}[] = languages;

  selectedLocale;

  ngOnInit() {
    this.selectedLocale = this.languageList.spanish;
  }
}

模板文件:

<p-calendar [(ngModel)]="value" name="test" [locale]="selectedLocale">
</p-calendar>

我得到:

Property 'spanish' does not exist on type '{}[]'.

这是我关注的: How to Read Local JSON file in Angular

这里是 stackblitz.

请指出我的错误

试试这个:

languageList: {
    'DatePickerLanguages'
  }  = languages;

ngOnInit() {
    this.selectedLocale = this.languageList.DatePickerLanguages[0].spanish;
}

如果您可以控制 JSON 文件。我建议您将 JSON 修改为:

{
    "DatePickerLanguages": {   // Initialized it as object instead of array. 
            "spanish": {
                  ....
            },
            "german": {
                  ....
            }
    }
}

并使用以下方式访问西班牙语:

this.selectedLocale = this.languageList.DatePickerLanguages.spanish;

根据您评论中的要求:

在我的回答中使用第零个索引的原因是因为在您的 JSON 中 "DatePickerLanguages": 是一个数组 []。 属性 spanish 位于数组的第零个索引中。