Call method on lazy loaded class

25 views
Skip to first unread message

TiDiDoDa

unread,
Oct 20, 2017, 10:31:10 AM10/20/17
to Angular and AngularJS discussion
Hello everyone,

i've got a problem while using angular 4.4.5: i'm loading some events from my backend server. These events i want to show in my frontend. For my images i need to put an url suffix, so i decided to provide a public method in my class "Event". In my html-file i want to call the method but it throws and exception:

ERROR TypeError: _co.event.getImageUrl is not a function
    at Object.eval [as updateDirectives] (FrontPageComponent.html:35)
    at Object.debugUpdateDirectives [as updateDirectives] (vendor.js:13425)
    at checkAndUpdateView (vendor.js:12609)
    at callViewAction (vendor.js:12957)
    at execEmbeddedViewsAction (vendor.js:12915)
    at checkAndUpdateView (vendor.js:12610)
    at callViewAction (vendor.js:12957)
    at execComponentViewsAction (vendor.js:12889)
    at checkAndUpdateView (vendor.js:12615)
    at callViewAction (vendor.js:12957)

Thats the code to get all my events:
loadEvents(): Observable<Event[]> {
 
return this.http.get(environment.backendUrl + "events")
   
.map(response => response.json());
}


In my component i call this method as following:
this.eventService.loadEvents().subscribe(
 
(events) => {
   
// I just want the first event
   
this.eventEntry = events[0];
 
},
 
(error) => {
   
// ...
   
console.error(error);
 
}
);

I've got the class "Event":
export class Event{
    // ...
   
image: string;

   
getImageUrl(): string {
     
if (this.image) {
        return environment.siteUrl + this.image;
     
}

     
return '';
    }
}


And in my html file it looks like this:
{{ eventEntry.getImageUrl() }}

// for an custom selector it also does not work
<anExample [image]="eventEntry.getImageUrl()"></anExample>


I hope someone can help me

Sander Elias

unread,
Oct 26, 2017, 10:30:23 PM10/26/17
to Angular and AngularJS discussion
Hi TiDiDoDa,

Can you reproduce your issue in a stackblitz or plunker? that way it would be so much easier to help you.
The problem lies somewhere in the parts of the code you are not showing here. my top 2 would be:
  1. service that is lazily loaded is used outside the scope of its module. allways put services in root, or use .forRoot
  2. use of a method that is detached of its instance somehow. Try doing something like this in your event class:
    class event{
       constructor
    () {
         
    this.getImage = this.getImage.bind(this)
       
    }
    }
    as that will hard bind the method to the class
Regards
Sander
Reply all
Reply to author
Forward
0 new messages