我正在学习 Angular。 (版本 11)。
我不太确定我错过了什么。我正在从我的服务调用 API 以获取 JSON 对象并将其返回到我创建的接口对象中。
但是,当我查看 html 中的 country 值时,它不是我的国家/地区界面,而是来自 api 的完整对象。 (我的界面应该只有一个值的子集)。
服务:
getCountry(): void {
const name = this.route.snapshot.paramMap.get('name');
this.countryService.getCountry(name)
.subscribe(x => this.country = x);
};
组件:
export class CountryDetailComponent implements OnInit {
country: Country;
constructor(
private countryService: CountryService,
private route: ActivatedRoute
) { }
ngOnInit(): void {
this.getCountry();
const x = this.country;
}
getCountry(): void {
const name = this.route.snapshot.paramMap.get('name');
this.countryService.getCountry(name)
.subscribe(x => this.country = x);
};
国家:
export interface Country {
name: string,
alpha2Code: string,
alpha3Code: string,
capital: string,
region: string,
subregion: string,
population: number,
demonym: string,
area: number,
gini: number
flag: string
}
component.html
{{country | json}}
API:https://restcountries.eu/rest/v2/name/aruba?fullText=true
来自 html 的结果:
[ { "name": "Aruba", "topLevelDomain": [ ".aw" ], "alpha2Code": "AW", "alpha3Code": "ABW", "callingCodes": [ "297" ], "capital": "Oranjestad", "altSpellings": [ "AW" ], "region": "Americas", "subregion": "Caribbean", "population": 107394, "latlng": [ 12.5, -69.96666666 ], "demonym": "Aruban", "area": 180, "gini": null, "timezones": [ "UTC-04:00" ], "borders": [], "nativeName": "Aruba", "numericCode": "533", "currencies": [ { "code": "AWG", "name": "Aruban florin", "symbol": "ƒ" } ], "languages": [ { "iso639_1": "nl", "iso639_2": "nld", "name": "Dutch", "nativeName": "Nederlands" }, { "iso639_1": "pa", "iso639_2": "pan", "name": "(Eastern) Punjabi", "nativeName": "ਪੰਜਾਬੀ" } ], "translations": { "de": "Aruba", "es": "Aruba", "fr": "Aruba", "ja": "アルバ", "it": "Aruba", "br": "Aruba", "pt": "Aruba", "nl": "Aruba", "hr": "Aruba", "fa": "آروبا" }, "flag": "https://restcountries.eu/data/abw.svg", "regionalBlocs": [], "cioc": "ARU" } ]
答案 0 :(得分:1)
您缺少一些基本概念:
API 返回一个国家/地区数组(只有一个值),因此保存此值的变量应为:
this.countryService.getCountry(name).subscribe(x => this.country = x[0]);
接口用于静态类型检查,在运行时没有接口,因为代码被转译为 Javascript 而接口在 JS 中不存在。 Interface
的使用方式与您的使用方式不同。
这里有一个很好的阅读:https://www.typescriptlang.org/docs/handbook/interfaces.html
name: string;
alpha2Code: string;
alpha3Code: string;
capital: string;
region: string;
subregion: string;
population: number;
demonym: string;
area: number;
gini: number;
flag: string;
constructor(d: any) {
this.name = d.name;
...
}
}
答案 1 :(得分:0)
如果您想去除额外的属性,您需要一个 class
。 interface
实际上什么都不做。它严格来说是模型的数据契约或模式。如果你设置了一些东西并且有额外的属性,它们将在界面上设置。
class Country {
name: string;
alpha2Code: string;
alpha3Code: string;
capital: string;
region: string;
subregion: string;
population: number;
demonym: string;
area: number;
gini: number;
flag: string;
constructor(d: any) {
this.name = d.name;
this.alpha2Code = d.alpha2Code;
...
}
}