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);
});
}
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);
});
}
Share
Improve this question
asked Aug 2, 2018 at 16:00
prevoxprevox
5763 gold badges11 silver badges23 bronze badges
1
-
1
Filter is an array method. Is
res
an array? – Mark Commented Aug 2, 2018 at 16:02
4 Answers
Reset to default 8filter
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.
I think your res in not array please check type of res, if it is array then filter method work.
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))
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 piler.
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 pilation. 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 piler doesn't check)
let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.