[英]define interface for json object response
My API returns following JSOn response: 我的API在JSOn响应后返回:
{
key1: [
name: "bob",
gender: "male",
children: [
{
name: "tom",
gender: "male"
},
{
name: "charley",
gender: "male"
}
]
],
key2: {
bob: 45,
tom: 15,
charley: 10
}
}
I have declared type 'any' for the response in my component.ts: 我在component.ts中声明了类型为“ any”的响应:
export class personComponent implements OnInit {
personData: any[];
}
this._personService.getPersonData().subscribe(personData = > {
this.data = personData;
}, error => this.errorMessage = <any>error, () => {
this.personObject = this.data.key1; // Here it throws error - 'key1' doesnt exists on type any[];
})
I know the way to create interface for objects and array.. but how I can create interface for a JSON ouput. 我知道为对象和数组创建接口的方法。但是我如何为JSON输出创建接口。
Can anyone please help me here. 任何人都可以在这里帮助我。
In your Module import HttpClientModule instead of old HttpModule. 在您的模块中导入HttpClientModule而不是旧的HttpModule。
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [ HttpClientModule ]
})
[...]
Your output looks a little weird. 您的输出看起来有点奇怪。 An interface maybe could look like:
接口可能看起来像:
export interface PersonData {
[key: string]: {
name?: string;
gender?: string;
children?: Array<{name: string, gender: string}>
[key: string]: any; // optional
}
}
In your service then use the HttpClient which provides kind of a type parser 在您的服务中,然后使用HttpClient,它提供了一种类型解析器
import { HttpClient } from '@angular/common/http';
[...]
constructor(private http: HttpClient) {}
getPersonData(): Observable<PersonData> {
return this.http.get<PersonData>(url);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.