I have a component that creates an object (of type TableDataSource) and in the constructor I am also passing in a method that returns a promise (save method), however when the method gets called by TableDataSource, the service the method belongs to is not defined.
How would I go about injecting the service into TableDataSource given that it has to be generic. In this case I need a method that belongs to ContactService, but in another component I would need UserService for instance.
@Component({
selector: 'app-contact-details',
})
export class ContactDetailsComponent {
constructor(
private contactService: ContactService,
)
{
this.dataSource = new TableDataSource<IContactDetail>(this.save);
}
public save(item: IContactDetail): Promise<IContactDetail[]> {
return this.contactService.save(item); <--- this.contactService is null
}
}
This is the TableDataSource:
export class TableDataSource<T> extends DataSource<TessTableRow<T>> {
protected save: (data: T) => Promise<T | T[]>;
constructor(
save: (data: T) => Promise<T | T[]>
) {
super();
this.save = save;
}
}
In this case you need to bind the context to save
method because when you assign the method in another variable and call this method through that variable you have lost the original context:
this.dataSource = new TableDataSource<IContactDetail>(this.save.bind(this));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments