簡體   English   中英

定義json對象響應的接口

[英]define interface for json object response

我的API在JSOn響應后返回:

{
  key1: [
    name: "bob",
    gender: "male",
    children: [
      {
        name: "tom",
        gender: "male"
      },
      {
        name: "charley",
        gender: "male"
      }
    ]
  ],
  key2: {
    bob: 45,
    tom: 15,
    charley: 10
  }
}

我在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[];
})

我知道為對象和數組創建接口的方法。但是我如何為JSON輸出創建接口。

任何人都可以在這里幫助我。

在您的模塊中導入HttpClientModule而不是舊的HttpModule。

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [ HttpClientModule ]
})
[...]

您的輸出看起來有點奇怪。 接口可能看起來像:

export interface PersonData {
  [key: string]: {
    name?: string;
    gender?: string;
    children?: Array<{name: string, gender: string}>
    [key: string]: any; // optional
  }
}

在您的服務中,然后使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM