我正在使用Typescript開始一個新項目,從中我沒有以前的經驗。我想用d3.xhr方法做一些HTTP請求,但目前爲止沒有取得太大的成功。見下面的相關代碼段:無法使用d3類型觸發POST-JSON請求
private buildBody(query: string): any {
return {
statements: [{
statement: query
}]
}
}
exec(query: string) {
d3.xhr(this.baseURL)
.header('Content-Type', 'application/json')
.post(buildBody(query), (error, data) => {
if (error){
console.error(error);
} else {
console.log(data);
}
});
}
這似乎是無效的。有一個看看D3類型的定義,有件事情我真的不明白:
post: {
/**
* Issue the request using the POST method
*
* @param callback Function to invoke on completion of request
*/
(callback?: (xhr: XMLHttpRequest) => void): Xhr;
/**
* Issue the request using the POST method
*
* @param data Data to post back in the request
* @param callback Function to invoke on completion of request
*/
(data: any, callback?: (xhr: XMLHttpRequest) => void): Xhr;
};
POST請求回調預計(xhr: XMLHttpRequest) => void
類型,而D3 API預計一些兩個參數的函數。 Typescript中通常定義的回調是怎樣的? post方法(回調類型)定義實際上是否正確?
在此先感謝。
這是正確的,但不是我的問題。我的問題是回調類型('(xhr:XMLHttpRequest)=> void')是否正確,因爲有了這樣的定義,我無法觸發任何單個請求。我會更新我的問題,使之更清晰。 – jarandaf
編輯我的答案來反映這一點。 – Nypan
我創建了一個PR,看來類型定義確實是錯的。我會接受你的答案,謝謝你的時間。 – jarandaf