在查询字符串中的可选参数

huangapple go评论49阅读模式
英文:

optional parameter in query string

问题

我想使查询字符串中的fio参数成为可选项,如果为空则不发送。查询字符串将如下所示:

http://localhost:5025/EventLog/FromPeriod?DateIn=2023-02-08T11%3A50%3A10.198Z&DateOut=2023-02-08T11%3A50%3A10.198Z&idPunkts=18

我尝试在我的服务方法中添加?fio: string,但出现了类型错误。我还尝试在API控制器中添加null,但仍然不起作用。

请注意,将fio参数设置为可选项需要对您的代码进行一些更改。您可以尝试以下方法:

在服务方法中将fio参数更改为可选的,并检查其是否存在,然后相应地构建参数:

updateFromPeriod(DateIn: any, DateOut: any, idPunkts: any, fio?: string) {
  let params = new HttpParams()
    .append('DateIn', this.toISOLocal(DateIn))
    .append('DateOut', this.toISOLocal(DateOut))
    .appendAll({ 'idPunkts': idPunkts });

  if (fio) {
    params = params.append('fio', fio);
  }

  const options = {
    params,
    headers: new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Authorization', `Bearer ${this.authService.currentSessionValue.token}`)
  };

  console.log('PARAMS: ' + options.params);

  return this.httpClient.get<EventLog[]>(this.BaseUrl + 'EventLog/FromPeriod', options);
}

这样,如果fio参数存在,它将包含在查询字符串中,如果不存在,它将被忽略。

然后,在您的API控制器中,不需要任何其他更改,因为你已经正确处理了可选的fio参数。

英文:

i have the text field 'fio' in my search form, which can be empty.

home.html:

&lt;dx-text-box
          [(value)]=&quot;fio&quot;         
        &gt;&lt;/dx-text-box&gt;

this is my component and service to send the search parametres for API

component:

public fio!: string;


public updateFromPeriod(): void {
  
    this.updateService.updateFromPeriod(this.DateIn, this.DateOut, this.punktsID(this.punktValue), this.fio).subscribe({
        next: value =&gt; {
      
          this.EventLogs = value;
        },
        error: err =&gt; {
          console.error(err);
        }
    });

service:

updateFromPeriod(DateIn: any,
        DateOut: any,
        idPunkts: any,
        fio: string) {
            const options = {
                params: new HttpParams().append(&#39;DateIn&#39;, this.toISOLocal(DateIn)).append(&#39;DateOut&#39;, this.toISOLocal(DateOut)).appendAll({&#39;idPunkts&#39;: idPunkts})
                .append(&#39;fio&#39;, fio),
                headers: new HttpHeaders().set(&#39;Content-Type&#39;, &#39;application/json&#39;).set(&#39;Authorization&#39;, `Bearer ${this.authService.currentSessionValue.token}`)
              };
              console.log(&#39;PARAMS: &#39; + options.params);
      return this.httpClient.get&lt;EventLog[]&gt;(this.BaseUrl +&#39;EventLog/FromPeriod&#39;, options);
    }

and server method:

public IEnumerable&lt;EventLog&gt; Get(
        [FromQuery] DateTime DateIn, 
        [FromQuery] DateTime DateOut, 
        [FromQuery] int[] idPunkts, 
        [FromQuery] string fio)         {             
    List&lt;int&gt; punkts = idPunkts.ToList();             
    var login = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;             
    return EventLogRepository.GetEventLog(DateIn, DateOut, punkts, fio, login);
}

I want to make the fio parameter optional in query string, which will not send, if it's empty. And the query string will be like this

http://localhost:5025/EventLog/FromPeriod?DateIn=2023-02-08T11%3A50%3A10.198Z&amp;DateOut=2023-02-08T11%3A50%3A10.198Z&amp;idPunkts=18

i try to add ?fio: string in my service method, but have the type mistake. Als i tried to add null on api controller, but it still doestn work.

答案1

得分: 0

你应该根据条件将它附加到你的参数中:

let params: HttpParams = new HttpParams().append('DateIn', this.toISOLocal(DateIn)).append('DateOut', this.toISOLocal(DateOut)).appendAll({'idPunkts': idPunkts});
if (fio) { params = params.append('fio', fio); }
const options = {
    params: params,
    headers: new HttpHeaders().set('Content-Type', 'application/json').set('Authorization', `Bearer ${this.authService.currentSessionValue.token}`)
};

可能有更优雅的方法,但这是基本原则。

英文:

you should conditionally append it to your params:

let params:HttpParams = new HttpParams().append(&#39;DateIn&#39;, this.toISOLocal(DateIn)).append(&#39;DateOut&#39;, this.toISOLocal(DateOut)).appendAll({&#39;idPunkts&#39;: idPunkts});
if(fio){ params = params.append(&#39;fio&#39;, fio);}
const options = {
            params: params,
            headers: new HttpHeaders().set(&#39;Content-Type&#39;, &#39;application/json&#39;).set(&#39;Authorization&#39;, `Bearer ${this.authService.currentSessionValue.token}`)
          };

There is probably more elegant way but that's the basic principle.

huangapple
  • 本文由 发表于 2023年2月8日 20:38:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定