简体   繁体   中英

Property 'filter' does not exist on type 'Object'

After updating my code to HttpClient I can't get filter() to work with the response. I keep getting Property 'filter' does not exist on type 'Object':

TS :

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

filter is an array method which cannot be used for objects in your case res .

First check if res is an array.

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

Or set type to res as (res: Array<any>)

If your api is returning an object, in most cases it should be, you can't use filter method here, you should be using it for an array inside res object.

Change this line:

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

to this:

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

or better yet to this:

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

and you should be able to bypass your typechecking error at the compiler.

Here is some more info from the official docs :

The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation. You might expect Object to play a similar role, as it does in other languages. But variables of type Object only allow you to assign any value to them - you can't call arbitrary methods on them, even ones that actually exist:

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'.

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

Either the object is null or it is not an array
try to check if the object is not null and is an array with
if(res != null && Array.isArray(res))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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