Angular 为什么http get attr[params]需要是{[param:string]:string | string[]}? 问题描述
this.http.get()在类型推断中出错Angular 为什么http get attr[params]需要是{[param:string]:string | string[]}? 问题描述,angular,angular11,Angular,Angular11,this.http.get()在类型推断中出错 error TS2322: Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<IInfo[]>'. Type 'ArrayBuffer' is missing the following properties from type 'IInfo[]': length, pop, push, concat, and 27 more.
error TS2322: Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<IInfo[]>'.
Type 'ArrayBuffer' is missing the following properties from type 'IInfo[]': length, pop, push, concat, and 27 more.
但我认为在get类型声明中将
{[param:string]:string | string[]}
转换为{[param:string]:any}
可能更合适我在处理请求参数时经常使用的模式是:
yourServiceMethod(requestParams:YourInterface):可观察{
设params=newhttpparams();
Object.keys(requestParams).forEach(key=>params=params.append(key,requestParams[key]);
返回此.httpClient
.get(this.baseUrl,{params})
.烟斗(
映射(响应=>响应),
catchError(()=>of(null)),
);
}
当然,您可以创建一个共享函数来完成从对象到HttpParams的转换。在一天结束时,这些值必须转换为字符串以通过查询字符串传递,因此Angular提出了接口要求。是的,这是我的func
generateHttpParams
的工作~Thx,用于共享,我认为Angular可能会使用任何更合适或不合适的方法?酷。我在您的代码中看到了这一点,但在实现中没有看到。我只在极少数情况下使用any
。通常,如果您确实不知道某个类型,则更适合将其键入为未知
,然后转换到另一个接口或类型。在我看来,使用any
会给自己带来麻烦。哦,我明白了,我添加了有问题的提示。
// tool function
function generateHttpParams(params: Object): HttpParams; // parse obj to HttpParams
// parse to HttpParams
getInfo(queryDataParams: IQueryParams): Observable<IInfo[]> {
return this.http.get<IInfo[]>(`xxx.com`, {
params: generateHttpParams(queryDataParams)
});
}
// set as any
getInfo(queryDataParams: IQueryParams): Observable<IInfo[]> {
return this.http.get<IInfo[]>(`xxx.com`, {
params: queryDataParams as any
});
}