Angular 如何在HttpParams中使用具有可空字段的对象?

Angular 如何在HttpParams中使用具有可空字段的对象?,angular,typescript,angular-httpclient,Angular,Typescript,Angular Httpclient,编写使用对象查询参数的Angular REST客户端时,以下代码按预期工作: search(params: {query: string, page: number, size: number}): Observable<any> { let p = new HttpParams({fromObject: params}); return this.http.get('http://localhost', {params: p}); } 与第一个示例类似,有

编写使用对象查询参数的Angular REST客户端时,以下代码按预期工作:

  search(params: {query: string, page: number, size: number}): Observable<any> {
    let p = new HttpParams({fromObject: params});
    return this.http.get('http://localhost', {params: p});
  }

与第一个示例类似,有没有一种方法可以将其缩短,但仍然允许使用可选参数?

es6
中,您可以这样简单地进行操作


search(参数:{query?:string,page?:number,size?:number}={}):在
es6
中可以观察到


search(参数:{query?:string,page?:number,size?:number}={}):可观察的

您可以使用typescript
作为
关键字。大概是这样的:

// Define the type outside of the class.
type ParamOptions = { [param: string]: string | readonly string[]; }




// now you can use the type
search(params: { query?: string; page?: number; size?: number } = {}): Observable<any> {
        const p = new HttpParams({ fromObject: params as ParamOptions});
        return this.http.get("http://localhost", { params: p });
}
//在类之外定义类型。
键入ParamOptions={[param:string]:string |只读字符串[];}
//现在您可以使用该类型
搜索(参数:{query?:字符串;页面?:编号;大小?:编号}={}):可观察{
const p=新的HttpParams({fromObject:params as ParamOptions});
返回此.http.get(“http://localhost“,{params:p});
}

您可以将typescript
用作关键字。大概是这样的:

// Define the type outside of the class.
type ParamOptions = { [param: string]: string | readonly string[]; }




// now you can use the type
search(params: { query?: string; page?: number; size?: number } = {}): Observable<any> {
        const p = new HttpParams({ fromObject: params as ParamOptions});
        return this.http.get("http://localhost", { params: p });
}
//在类之外定义类型。
键入ParamOptions={[param:string]:string |只读字符串[];}
//现在您可以使用该类型
搜索(参数:{query?:字符串;页面?:编号;大小?:编号}={}):可观察{
const p=新的HttpParams({fromObject:params as ParamOptions});
返回此.http.get(“http://localhost“,{params:p});
}

不幸的是,这不起作用。Typescript返回的'Type'{query?:string |未定义;page?:number |未定义;size?:number |未定义;}'不可分配给类型'{[param:string]:string | readonly string[];}'@Paul const p=new HttpParams({fromObject:{…params});应该可以工作,但不幸的是,这不起作用。Typescript返回'Type'{query?:string |未定义;page?:number |未定义;size?:number |未定义;}不可分配给类型“{[param:string]:string | readonly string[];}”`@Paul const p=new HttpParams({fromObject:{…params});应该可以工作