Angular HTTP服务清除RequestOptions搜索参数 [英] Angular http service clear RequestOptions search parameters

查看:53
本文介绍了Angular HTTP服务清除RequestOptions搜索参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果未定义值,则无需在URL中传递任何查询参数.在AngularJS中,当将某些类型的参数传递到 $ resource 服务中并且其值为空或未定义时,则永远不会将其附加到URL字符串,但是在Angular中,Http服务及其RequestOptions对象一起用于设置标题和参数的行为有所不同.

I need to not pass in any query parameters in the URL if the value not defined. In AngularJS when some sort of parameters were passed into $resource service and its value was empty or not defined, then it was never appended to the URL string, however in Angular the Http service along with its RequestOptions object which is used to set headers and parameters behaves differently.

例如,此输入元素:

<select class="form-control form-control-sm" formControlName="catalogCode" title="Catalog Code">
    <option value="">- Catalog Code -</option>
    <option *ngFor="let option of codes" [value]="option.code">
      {{ option.text }}
    </option>
  </select>

这将更新我已定义的 QueryParameters ,并将其用于以下服务:

This updates the QueryParameters I have defined and it is used in service like this:

getOfferings(parameters: QueryParameters): Observable<Offering[]> {
    let requestOptions = new RequestOptions({
      search: {
        catalogCode: parameters.catalogCode
      }
    });

    return this.http.get(`${environment.BASE_URL}/offerings`, requestOptions)
      .map(response => response.json());
  };

如果已填充 parameters.catalogCode ,则查询运行正常且URL看起来正确: http://localhost:4200/offerings?catalogCode = CODE1 ,但是当我从列表中选择空选项,URL将为?catalogCode = ,其值为空.

If the parameters.catalogCode is populated, query runs fine and the URL looks proper: http://localhost:4200/offerings?catalogCode=CODE1, however when I select the empty option from the list, the URL will be ?catalogCode= with empty value.

不幸的是,我的后端不喜欢空的 catalogCode ,所以我真的想防止这种情况发生,因为它曾经在旧的Angular中使用.有清除它的适当方法吗?

My backend unfortunately does not like the empty catalogCode so I would really like to prevent that as it used to be in old Angular. Is there any proper way of clearing it?

推荐答案

您必须自己做.这样做很好,因为您可以选择所需的确切行为,而不是建立在外部库隐含的虚假行为之上.

You'll have to do that yourself. Which is good because you get to choose the exact behaviour you need, instead of building on the hidden opinionated falsy-behaviour of an external library.

在lodash中执行此操作的一些方法:

Some ways to do this in lodash:

const search = {
  catalogCode: parameters.catalogCode
};

const requestOptions = new RequestOptions({
  // only remove undefined, my preferred option
  search: _.omitBy(search, _.isUndefined)
});

  // remove undefined and null (but not empty strings or the number 0)
  search: _.omitBy(search, _.isNil)

  // remove undefined, null, and empty string (but still not the number 0)
  search: _.omitBy(search, x => _.isNil(x) || x === '')

这篇关于Angular HTTP服务清除RequestOptions搜索参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆