angular - 删除 HttpParams 中的空参数

标签 angular query-string asp.net-core-2.0 asp.net-core-webapi querystringparameter

我有一个标准对象,它的一些属性可以为空,如果我什么都不做,查询字符串包括像 &p=undefined 这样的东西,这是不可取的,因为在 WebApi 中,这些是"null" 而不是 null 所以在 Angular 客户端中给出这个

      return this._http
          .get<ExposureDifference[]>(AppSettings.ExposureRunDataQueryString, {params : <any>criteria, withCredentials: true}) 
          .catch<any, ExposureDifference[]>(this._trace.handleError("GET " + AppSettings.ExposureRunDataQueryString + criteria, []))
          .finally(() => this.isLoading = false);

我可以得到查询字符串为

http://localhost:63037/api/exposureRuns/data/?id=3&secsymb=undefined&fund=EL&esectype=SWAP_CDS

有没有办法从查询字符串中排除未定义的参数?

最佳答案

您应该使用 JavaScript 的 delete (MDN) 在客户端过滤它们关键字,如果它们的值为 undefined(这与根本不在对象中的键不同):

if (queryObject.secsymb === undefined) {
  delete queryObject.secsymb;
}

然后在您的 Controller 方法中使用默认方法参数:

GetExposureRunsData(int id, string fund, SecType sectype, string secsymb = null)

如果您确保不包含查询字符串参数,那么您的参数将默认为 null

关于angular - 删除 HttpParams 中的空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47707943/

相关文章:

javascript - 对 JavaScript 单页 Web 应用程序进行版本控制? (请求参数)

error-handling - 如何判断哪个 Controller 引发了异常

asp.net-core - .net core 2.0 - 值不能为空。参数名称: key

javascript - typescript 类不接受参数类型

angular - Service Worker 注册失败,错误为 : TypeError: Failed to register a ServiceWorker for scope

angular - 隐藏/屏蔽辅助路由 Angular 4 的 URL

angular - 双向绑定(bind) - 嵌套对象 - Angular - 无法读取未定义的属性

.htaccess - 301 Htaccess 重写规则查询字符串

asp.net-core - ASP .NET Core 2 中的字符串修剪模型绑定(bind)器