【问题标题】:Angular 6 HttpClient set param date only if its not nullAngular 6 HttpClient 仅在其不为空时才设置参数日期
【发布时间】:2019-02-23 18:02:38
【问题描述】:

我正在尝试将参数传递给 URL。我正在为此使用 Angular HttpParams。仅当日期不为空或未定义时,如何设置日期参数?

代码:

let params = new HttpParams()
   .set('Id', Id)
   .set('name', name)

if (startDate !== null) {
    params.set('startDate', startDate.toDateString());
}

if (endDate !== null) {
    params.set('endDate', endDate.toDateString());
}

【问题讨论】:

    标签: angular typescript angular6


    【解决方案1】:

    set 不会改变它正在处理的对象 - 它返回一个带有新值集的新对象。你可以使用这样的东西:

    let params = new HttpParams()
       .set('Id', Id)
       .set('name', name)
    
    if (startDate != null) {
        params = params.set('startDate', startDate.toDateString());
    }
    
    if (endDate != null) {
        params = params.set('endDate', endDate.toDateString());
    }
    

    注意params 对象是如何被重新分配的。还要注意使用!= 来防止nullundefined

    【讨论】:

    • 你应该避免避免 != null 除了 "boolean",一般你只需要写 if(startDate) { if(endDate) {
    • @xrobert35 是的,我知道这是一个敏感区域 - This 说我使用的东西很好用(this 也是如此)。
    • @xrobert35 我有参数“page”,所以,page=0 对我来说是一个有效的参数,if (page) 会是假的,但不会是……
    • 请投票支持有条件的 HttpParams 集更新功能:github.com/angular/angular/issues/26021
    【解决方案2】:

    除了使用 HttpParams 对象,您还可以定义和改变自己的对象并在 http 调用中传递它。

    let requestData = {
      Id: Id,
      name: name
    }
    if (startDate) {
    //I am assuming you are using typescript and using dot notation will throw errors 
    //unless you default the values
      requestData['startDate'] = startDate
    }
    if (endDate) {
      requestData['endDate'] = endDate
    }
    
    //Making the assumption this is a GET request
    this.httpClientVariableDefinedInConstructor.get('someEndpointUrl', { params: requestData })
    

    【讨论】:

    • 想象 page 参数而不是 startDate... page 设置为 0 将失败您的 set...
    • 不仅如此,requetData[page] == requestData[0]... 不好(可能是requestData['page']
    • 感谢您对缺少的引号进行更正,在您的情况下,您可以执行 if(page!==undefined && page!==null)。此时您仍然可以将页面属性分配给对象。
    猜你喜欢
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2012-03-10
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多