【问题标题】:Rewrite fetch call to oboe for json streams with Typescript使用 Typescript 为 json 流重写对双簧管的 fetch 调用
【发布时间】: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


    【解决方案1】:
    • 错误意味着Oboe 类/类型不是通用的。以NumberString 为例
    • Oboe's docs 看来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);
            });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多