【问题标题】:Javascript Axios get with conditional paramsJavascript Axios 获取条件参数
【发布时间】:2021-08-17 03:18:03
【问题描述】:

我正在尝试从 API 获取一些数据。问题是 GET 调用可能不采用或采用某些过滤器。我已经尝试过,但不确定如何/是否可以使用条件过滤器创建 URL。

actions: {
        InstitutionSearch(value, id){
let fips = id['ParamValues'].find(o=>o.param==='fips')['value'];
            let region = id['ParamValues'].find(o=>o.param==='region')['value'];
axios.get('https://educationdata.urban.org/api/v1/college-university/ipeds/directory/2019/',{
                params:{
                     fips: ,
                     region: region,
                     offering_highest_level: 3
                }
})
};
}

这是一个 vue 应用程序,上面的代码在 vuex 存储中运行。传入的 id 是一个对象数组,取自搜索过滤器表单。我遇到的问题是我的查询可能包含 fips 或 region 或不包含。

我最初的想法是 put fips 和 region 等于 0,但这不适用于我的 API。我不反对在条件句中构建查询字符串,但必须有更简单的方法。以下是对我正在使用的数据的实际查询https://educationdata.urban.org/api/v1/college-university/ipeds/directory/2019/?offering_highest_level=3

【问题讨论】:

    标签: javascript vue.js axios vuex


    【解决方案1】:

    在一些惊人的帮助下,我想出了一个简单的解决方案。我创建了一个空对象,然后对我的参数进行条件检查,如果它们符合我的资格,则只添加它们。然后我将该对象作为参数传入,一切正常。

    let fips = id['ParamValues'].find(o=>o.param==='fips')['value'];
                let region = id['ParamValues'].find(o=>o.param==='region')['value'];
    //code change
                let params = {};
    
                fips.length > 0 ? params['fips'] = fips.join(',') : null;
                region != 0 ? params['region'] = region : null;
    //code change
                axios.get('https://educationdata.urban.org/api/v1/college-university/ipeds/directory/2019/',{
                    params
                }).then(response=>{
                    console.log(response.data.results);
                });
    

    【讨论】:

      【解决方案2】:
      useEffect(() => {
          axios
            .get(
              `http://stream-restaurant-menu-svc.herokuapp.com/item?category=${props.data}`
            )
            .then((response) => {
              console.log("This is to show sub-categoary " + response.data);
              setSubcate(response.data);
            })
            .catch((error) => {
              console.log(error);
            });
        },[props]);
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 2019-03-14
      • 2015-10-30
      • 1970-01-01
      • 2021-11-30
      • 2022-12-01
      • 1970-01-01
      相关资源
      最近更新 更多