我想從后端獲取 JSON 型別的資料,但 JSON 的型別必須是通用的。它具有通用數量的值和通用鍵,我怎樣才能正確撰寫 get 方法?暫時我寫這個:
getArticoliByDesc = (descrizione : string) => {
return this.httpClient.get<{
this.nomeChiave:
}[]>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT 0096 | ALT GR '
}
我不知道我必須在<>
括號中寫什么。
uj5u.com熱心網友回復:
您可以將型別添加為 JSON。打字稿中有一種型別。
示例代碼
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-array-json-dates',
templateUrl: './array-json-dates.component.html',
styleUrls: ['./array-json-dates.component.scss']
})
export class ArrayJsonDatesComponent implements OnInit {
jsonObject: JSON;
arrayObj: any = [
{
id: 1,
name: "john",
lastModified: '2011-01-01 02:00:00'
},
{
id: 2,
name: "Franc",
lastModified: '2001-01-01 02:00:00'
},
{
id: 3,
name: "Andrew",
lastModified: '2021-01-01 02:00:00'
},
{
id: 11,
name: "Mark",
lastModified: '2020-01-01 02:00:00'
},
{
id: 12,
name: "Eric",
lastModified: '2020-02-01 02:00:00'
},
{
id: 8,
name: "Tony",
lastModified: '1990-01-01 02:00:00'
}
]
constructor() {
this.jsonObject = <JSON>this.arrayObj;
}
ngOnInit(): void {
}
在你的情況下
getArticoliByDesc = (descrizione : string) => {
return this.httpClient.get<JSON>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT 0096 | ALT GR '
}
但是仍然創建一個與您的 api 回應相匹配的模型類將是最好的方法。即使 api 回傳 json,Angular http 也會將其轉換為物件。然后你可以通過添加你的模型來概括它
前任:
export class ApiModel{
property1: string;
property2: string;
property3: string;
}
getArticoliByDesc = (descrizione : string) => {
return this.httpClient.get<ApiModel>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT 0096 | ALT GR '
}
uj5u.com熱心網友回復:
如果您不知道回應型別并且您不關心輸入,您可以執行以下操作:
const result = client.get<any>('URL');
如果你知道回應是一個物件但你不知道屬性,你可以這樣做:
const result = client.get<{ [key: string]: unknown }>('URL');
// Or create an alias.
type Data = { [key: string]: unknown };
const result = client.get<Data>('URL');
// Or if you expect an array.
const result = client.get<Data[]>('URL');
如果您需要打字稿來檢查型別,那么您必須知道資料型別并為此創建型別。例如:
type User = {
name: string;
email: string;
}
如果您期望回應是一個用戶物件 =>{ name, email }
const result = client.get<User>('URL');
如果您期望回應是一個用戶物件陣列 =>[ { name, email } ]
const result = client.get<User[]>('URL');
如果您期望回應是已知字串變數的陣列:
type KnownVariables = Array<'doctor' | 'programmer' | 'designer'>;
const result = client.get<KnownVariables>('URL');
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/507225.html