使用Null而不是Undefined

时间:2019-05-14 18:30:36

标签: angular typescript angular6 angular7

在angular 7上,我具有以下界面:

export interface Request {
  limit?: number;
  offset?: number;
}

以及如下服务方法:

public get(request: Request): Observable<Response>> {

  const parameters = { 'limit': String(request.limit), 'offset': String(request.offset) };

  return this.httpClient.get<Response>>(`projects`, { params: parameters });

}

我从组件中按如下方式调用服务:

let request: Request = { offset: 20 };

projectService.get(request)

API返回错误:

The value 'undefined' is not valid for Limit.

我认为当limit不在请求中时,应该将其设置为null,对吧?

如何将undefined的值设置为null而不是undefined

4 个答案:

答案 0 :(得分:1)

let request: Request = { offset: 20, limit : null };

  

0 vs null vs undefined   Just to add more fun to it

答案 1 :(得分:1)

如果limitoffset为“可选”,则有3种可能性:

  • ?limit=undefined&offset=20 您的代码

服务

public get(request: Request): Observable<Response>> {
  const parameters = { 'limit': String(request.limit), 'offset': String(request.offset) };
  return this.httpClient.get<Response>>(`projects`, { params: parameters });
}

用法

let request: Request = { offset: 20 };
projectService.get(request);
  • ?offset=20

服务

public get(request: Request): Observable<Response>> {
  const parameters = {};
  if (request.limit) parameters.limit = String(request.limit);
  if (request.offset) parameters.offset = String(request.offset);
  return this.httpClient.get<Response>>(`projects`, { params: parameters });
}

用法

let request: Request = { offset: 20 };
projectService.get(request);
  • ?limit=null&offset=20

服务

public get(request: Request): Observable<Response>> {
  const parameters = { 'limit': request.limit ? String(request.limit) : 'null', 'offset': request.offset ? String(request.offset) : 'null' };
  return this.httpClient.get<Response>>(`projects`, { params: parameters });
}

用法

let request: Request = { offset: 20 };
projectService.get(request);

使用API​​想要的任何内容。

答案 2 :(得分:0)

const parameters = { 'limit': request.limit && typeof request.limit === "number" ? String(request.limit) : null, 
                     'offset': request.offset && typeof request.offset === "number" ? String(request.offset) : null };

答案 3 :(得分:0)

在大多数API中,limit参数是强制性的,因此它可以返回您所要求的限制数量。但是,如果您认为此API可以将null作为极限值,则可以使用三元运算符检查request.limit的值(如果它不是未定义的),然后将String(request.limit)设置为null。您可以对offset

做同样的事情
public get(request: Request): Observable<Response>> {

  const parameters = { 'limit': request.limit ? String(request.limit) : null, 'offset': request.offset ? String(request.offset) : null };

  return this.httpClient.get<Response>>(`projects`, { params: parameters });

}