Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to call functions on observable results

I have an interface (Vehicle), a class that implements it (Car) and has some method (isColorRed):

export interface Vehicle{
   color : string;
}

export class Car implements Vehicle{
   color : string;
   
   constructor(obj){
      this.color = obj.color;
   }

   isColorRed(){
   return color === 'red' ? true : false;
   }
}

I am getting an array of Cars from backend and want to store only ones that are red in color:

...
carsThatAreRed : Car[];
...
this.httpClient.get<Car[]>(carsUrl).pipe(
   map(cars => cars.filter(car => car.isColorRed()))
   ).subscribe(
   {
      next : (carsThatAreRed) => {
         this.carsThatAreRed = carsThatAreRed;
      }
   }
)

And this request fails and writes to dev console that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

isColorRed() is not a function

When I explicitly instantiate Car objects from each Car in the received array it works.

...
.pipe(
   map(cars => cars.map(car => new Car(car)).filter(car => car.isColorRed()))
   )
...

Why doesn’t it work without explicit mapping?

>Solution :

It’s a runtime error. You told TypeScript that its Cars you are getting, but at the runtime it’s just plain JSON objects, with no isColorRed method on them, unless you explicitly convert them to Cars. Sth along these lines

this.httpClient.get<Vehicle[]>(carsUrl)
    .pipe(
        map((vehicles) => vehicles.map(vehicle => new Car(vehicle))), // now we made Cars
        map(cars => cars.filter(car => car.isColorRed()))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading