我有这个提取电话:
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
但是我在使用oboe和打字稿(初学者)时遇到了问题(使用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
。
Oboe
类/类型不是通用的。就像Number
的String
一样oboe(param).done()
进行回调Promise
,并以与以前相同的方式完成其余操作Promise
api<T>(headers: Request): Promise<T> {
return new Promise((resolve, reject) => {
oboe(headers)
.done(data => resolve(data))
.fail(err => reject(err));
});
}
Promise/fetch
)componentDidMount(){
this.api<Array<Response>>(url, requestData)
.then(data => {
this.setState({
jobs: data
});
})
.catch(error => {
console.error(error);
});
}