akcasoy
akcasoy

Reputation: 7215

Angular Service's Dependencies are not injected when service function is used as Input parameter

We have some strange dependency injection problem which we do not understand... I try to demonstrate the situation.

We have an addressComponent where we inject our addressService. So this is the service (see the two injections http and appConfig):

@Injectable()
export class AdresseService{

  constructor(private http: Http, private appConfig: AppConfig) {
        ....
  }

  makeSth() {
      this.http.get(.....);
  }
}

This is the component:

export class AdresseComponent {

  constructor(public adresseService: AdresseService) {
  }
}

This component has this snippet in its html:

  <other-component-tag [fn]="adresseService.makeSth"</other-component-tag>

So we are injecting the service in component, and giving a function of this service as parameter to another component. And this is the other component, where we actually call this function:

export class OtherComponent {

  @Input() fn;

  callFunction() {
    this.fn();
  }
}

So the problem: The function "makeSth" of AdresseService is actually called, but the service dependencies (i.e. http or appConfig) are not injected. So we get some error like "get of undefined...." in the makeSth method of AdresseService. What is going on here?

When we define the service as a dependency of othercomponent it works. also when we give the whole service (instead of giving just a function of it) as parameter, it also works. But why does this setup not work?

Upvotes: 2

Views: 848

Answers (1)

Suraj Rao
Suraj Rao

Reputation: 29614

You are passing a class function as a callback. In this case, the value of this changes and the new this will not have http and other injected properties.

Use arrow function or a bound function as callback.

In your component,

export class AdresseComponent {

  makeSth:any;

  constructor(public adresseService: AdresseService) {
    this.makeSth = () => this.adresseService.makeSth()
  }
}

And in your html,

 <other-component-tag [fn]="makeSth"</other-component-tag>

Upvotes: 4

Related Questions