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

时间:2018-08-02 16:00:57

标签: javascript angular httpclient

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

TS

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

4 个答案:

答案 0 :(得分:2)

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

首先检查res是否为数组。

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

或将类型设置为res的{​​{1}}

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

答案 1 :(得分:0)

更改此行:

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>) => {

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

这是official docs的更多信息:

  

任何类型都是使用现有JavaScript的强大方法,   允许您在选择期间逐步选择加入和选择退出类型检查   汇编。您可能希望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'.

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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