使用Typescript为json流重写对oboe的提取调用

问题描述 投票:0回答:1

我有这个提取电话:

 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

reactjs typescript oboe.js
1个回答
2
投票
  • 该错误意味着Oboe类/类型不是通用的。就像NumberString一样
  • 来自Oboe's docs似乎oboe(param).done()进行回调
  • 您可以将该调用转换为Promise,并以与以前相同的方式完成其余操作

Replacing the callback logic with a Promise

api<T>(headers: Request): Promise<T> {
  return new Promise((resolve, reject) => {
    oboe(headers)
      .done(data => resolve(data))
      .fail(err => reject(err));
  });
}

Calling it (the way you did with Promise/fetch)

componentDidMount(){
    this.api<Array<Response>>(url, requestData)
        .then(data  => {
            this.setState({
                jobs: data
            });
        })
        .catch(error => {
            console.error(error);
        });
}
© www.soinside.com 2019 - 2024. All rights reserved.