Reputation: 78
I modified one of the original examples on angular2 website to demonstrate the problem:
http://plnkr.co/edit/Sz4i2JITJyNznIyZsNRM?p=preview
I am passing a Hero object in the click event of the tiles and trying to call the .speak() method of that object, but then an error is thrown - hero.speak is not a function.
sayHeroName(hero: Hero) {
hero.speak();
}
While debugging this I found that there are no methods on that object, only its properties
So, my question is if it is possible to access object's methods like this and what's the right way to do it.
Upvotes: 3
Views: 652
Reputation: 477
The problem is that Heroes in this list public heroes: Hero[] = [];
inside the app/dashboard.component.ts
are populated from app/mock-heroes.ts
via the app/hero.service.ts
.
When you look inside the app/mock-heroes.ts
you will notice that they are just plain JS Objects that's why there is no speak()
method on them.
To achieve your goal you will need to modify the app/mock-heroes.ts
to return a list of new Hero();
instead and modify the app/Hero.ts
constructor to accept the id
and name
as a parameter.
OR
Modify the app/hero.service.ts
to create the list of new Hero();
object instances based on the list from app/mock-heroes.ts
.
I hope this will nudge you in the right direction.
Upvotes: 2