繁体   English   中英

类型“对象”上不存在属性“过滤器”

[英]Property 'filter' does not exist on type 'Object'

将代码更新为HttpClient之后,我无法使用filter()处理响应。 我不断得到类型“对象”不存在属性“过滤器”:

TS

liqOnChange(selection): void  {
        this.http.get(this.json_liq).subscribe(res => {
            this.arr = res.filter(
                res => res.id == selection.target.value);
        });
}

filter是一个数组方法,在您的情况下res不能用于对象。

首先检查res是否为数组。

if(Array.isArray(res)){
   this.arr = res.filter(
                res => res.id == selection.target.value);
}

或将类型设置为res(res: Array<any>)

如果您的api在大多数情况下应该返回对象,则您不能在此处使用filter方法,而应将其用于res对象内部的数组。

更改此行:

this.http.get(this.json_liq).subscribe(res => {

对此:

this.http.get(this.json_liq).subscribe((res: any) => {

或对此更好:

 this.http.get(this.json_liq).subscribe((res: Array<any>) => {

并且您应该能够绕过编译器的类型检查错误。

这是来自官方文档的更多信息:

any类型是使用现有JavaScript的强大方法,可让您在编译过程中逐步选择加入和选择退出类型检查。 您可能希望Object像其他语言一样扮演相似的角色。 但是Object类型的变量仅允许您为其分配任何值-您不能在它们上调用任意方法,即使是实际存在的方法也是如此:

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

我认为您的资源不在数组中,请检查资源的类型,如果是数组,则过滤方法起作用。

该对象为null或不是数组
尝试检查对象是否不为null以及是否为数组
if(res != null && Array.isArray(res))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM