我读了 in this post 我可以在HttpParamsOptions中使用fromObject将对象用作查询的查询参数。不幸的是,我在使对象处于正确形状方面遇到一些问题。我认为它将能够使用具有所有类型字符串的对象,并且不确定如何将其转换为正确的形状。我宁愿不必遍历对象键来使事情适合此框-如果必须这样做,它会失去所有值。
有人可以向我解释这里发生了什么吗?我已经读过有关可索引类型的信息,但这并没有帮助我弄清楚如何将其应用于这种情况。
报告类型错误:
TS2322: Type '{ fromObject: Query; }' is not assignable to type 'HttpParamsOptions'.
Types of property 'fromObject' are incompatible.
Type 'Query' is not assignable to type '{ [param: string]: string | string[]; }'.
Index signature is missing in type 'Query'.
呼叫站点(以get中的{params:query}开头并分解为此):
public retrieve(query: Query): Observable<PolicyRetrieveResult> {
const q: HttpParamsOptions = {fromObject: query};
const params = new HttpParams(q);
return this.http.get<Result>(url, {params: params});
}
我的查询类:
export class Query {
id: string;
source: string = 'constant';
type: string = 'otherConstant';
}
这里是HttpParamsOptions供参考:
export interface HttpParamsOptions {
/**
* String representation of the HTTP params in URL-query-string format. Mutually exclusive with
* `fromObject`.
*/
fromString?: string;
/** Object map of the HTTP params. Mutally exclusive with `fromString`. */
fromObject?: {
[param: string]: string | string[];
};
/** Encoding codec used to parse and serialize the params. */
encoder?: HttpParameterCodec;
}
答案 0 :(得分:2)
由于您有字符串,因此要使其简单,我建议您改为执行以下操作:
public retrieve(query: Query): Observable<PolicyRetrieveResult> {
return this.http.get<Result>(url, {params: {...query}});
}
将来,如果您有非字符串对象,则正确的语法是
params: HttpParams = new HttpParams({ fromObject: query })
不要使用HttpParamsOptions
,当您看到它的来源时,就会明白为什么:
import { HttpParamsOptions } from '@angular/common/http/src/params';