Richard77
Richard77

Reputation: 21651

Injected services are null when I try to access them from the effect()

I've the notification, which is a signal object. I've a facade service that returned the object and also contains a set of methods.

when data arrives, I'm checking in the constructor using the effect whether the notification is self-dismissible. if that's the case, I start a timer then try to dismiss programmatically the notification. I keep the reference to the timer in a variable then dispose of it after the I dispatch the action to dismiss the notification.

The problem I'm having is that each time I call the dismissNotification from the effect, the sharedFacade is NULL, and it's throwing an error. Yet, the method is working just fine when it's called from the template.

Here's the component:

export class NotificationComponent {
 private sharedFacade = inject(SharedFacade);
 private timeoutFx: any;

 globalNotification = this.sharedFacade.globalNotification;

 constructor(){
  effect(() => {
    if(this.globalNotification().selfDismissable){
      this.timeoutFx = setTimeout(this.dismissNotification, 3000)
    }
   })
 }

 dismissNotification(){
   this.sharedFacade.dismissNotification(); //SharedFacade is null here
   if(this.timeoutFx){                      //when called from the timer
     clearTimeout(this.timeoutFx);
   }
 }
}

Upvotes: 1

Views: 29

Answers (1)

JSON Derulo
JSON Derulo

Reputation: 17708

When passing a function like you do in the setTimeout, a new this context is created. That's why everything you try to access via this inside the dismissNotification() function is not available. To fix it, you need to manually bind the context with the bind function:

this.timeoutFx = setTimeout(this.dismissNotification.bind(this), 3000);

Upvotes: 0

Related Questions