【发布时间】:2019-02-24 19:09:19
【问题描述】:
我有这个 fetch 调用:
api<T>(url: string, headers: Request): Promise<T> {
return fetch(url, headers)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json().then(data => data as T);
})
.catch((error: Error) => {
throw error;
});
}
componentDidMount(){
this.api<Array<Response>>(url, requestData)
.then(data => {
this.setState({
jobs: data
});
})
.catch(error => {
console.error(error);
});
}
但是我得到的响应是一个流+json,所以我在 .json() 处得到了无效的 json。
我看到有一个库可以帮助我:http://oboejs.com/examples
但我在使用双簧管和打字稿(初学者)(使用https://www.npmjs.com/package/@types/oboe)时遇到问题。
我试过了:
api<T>(headers: Request): Oboe<T> {
return oboe(headers)
.done(function(response) {
return response;
})
.fail(function(error: Error) {
throw error;
});
}
componentDidMount(){
this.api<Array<Response>>(requestData)
.done(data => {
this.setState({
jobs: data
});
})
.fail(error => {
console.error(error);
});
}
但是有明显的错误,因为我不知道双簧管应该返回什么类型,所以我收到错误Oboe is not generic。
【问题讨论】:
标签: reactjs typescript oboe.js