ackuser
ackuser

Reputation: 5899

Unable to run class's functions inside a particular function

I am using inside my template HTML on a custom component:

<foo ... (click)="doSth(foo)" ...></foo>

Then, in the controller I am calling a function belonging to the class of this particular object

class Foo {
      ...

      getWhatever(){
          ...
      }
}
doSth(foo: Foo) {
     foo.getWhatever();
     ....

At compile time, my IDE doesn't complain about anything. However, at runtime when I explicitly make that function to be executed I got:

FooListComponent.html:2 ERROR TypeError: foo.getWhatever is not a function

Doing a debugging, I see clear that it is not a Foo instance, instead is just a plain Object. If I try to do a cast or whatever similar nothing can help me to retrieve it like a Foo instance.

My guess is that it is treated as an Object coming from the template, should I do something like Instantiation Loader or similar?

Upvotes: 0

Views: 27

Answers (1)

bryan60
bryan60

Reputation: 29355

based on the comments, you need to be mapping your response into a class instance to access class methods:

this.http.get('foourl').pipe(map(fooResponse => new Foo(fooResponse))

this should get your code working, but it's questionable is this is a great design decision in general as using classes and class methods tends to cause a lot of pain in a javascript environment as stringifying and parsing loses all of your class functionality. I tend to prefer functional methods / style.

Upvotes: 1

Related Questions