ervin
ervin

Reputation: 549

Angular 11: inject service into a passed function

Let's say i have model class:

export class Model {
  id: number;
  editAction?: () => any;
}

then some component creates array of those object with defined function

  someArray: Model[];

  constructor(private readonly injectedService: InjectedService) {}

  private createObjects(): void {
    this.someApiService.getData().subscribe((data) => {
    this.someArray = data.map(x => 
      ({id: x.id, editAction: someEditAction})
    );
  }

  private someEditAction(): void {
    this.injectedService
      .open(/* ... */)
  }

then another one component, which has got someArray by an @Input() tries to invoke editAction for every element in HTML (it is all working properly):

Template:

<div *ngFor="let item of someArray">
  <button (click)="item.editAction()">
</div>

Component:
@Input() someArray: Model[];

The problem is that after we click this button, the function "someEditAction" is actually invoked, but it does not have dependencies from it's first component and it throws error that injectedService is null. Is there any way to inject this service into that function? InjectedService is of course decorated with providedIn: 'root' as usual. I tried to build factoryProvider, but I think i did it wrong

Upvotes: 1

Views: 661

Answers (1)

Aviad P.
Aviad P.

Reputation: 32680

Instead of this:

({id: x.id, editAction: someEditAction})

Write this:

({id: x.id, editAction: () => this.someEditAction()})

This will maintain the proper this.

EDIT: Having said that, a design change in the spirit of @DeborahK's comment above should be considered.

Upvotes: 2

Related Questions