简体   繁体   中英

define interface for json object response

My API returns following JSOn response:

{
  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:

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.

Can anyone please help me here.

In your Module import HttpClientModule instead of old 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

import { HttpClient } from '@angular/common/http';
[...]
constructor(private http: HttpClient) {}

getPersonData(): Observable<PersonData> {
  return this.http.get<PersonData>(url);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM