Skip to content

Instantly share code, notes, and snippets.

@Armenvardanyan95
Created February 17, 2025 09:53
Show Gist options
  • Save Armenvardanyan95/aa1db91c7ff42c9378b94926c135b9b6 to your computer and use it in GitHub Desktop.
Save Armenvardanyan95/aa1db91c7ff42c9378b94926c135b9b6 to your computer and use it in GitHub Desktop.
@Injectable()
export class DataService {
// here the name is getData
getData() {}
}
@Injectable()
export class SomeDataService {
// here the name is getSomeOtherData
getSomeOtherData() {}
}
@Component({...})
export class ReusableComponent {
// uses the DataService
readonly #dataService = inject(DataService);
}
// if we want to make the `ReusableComponent`
// use another service, we can create an
// adapter and use DI magic to force another instance
// on the child component
// here is an adapter, make sure it implements
// the service that that `ReusableComponent` uses
@Injectable()
export class DataServiceAdapter implements DataService {
readonly #someDataService = inject(SomeDataService);
getData() {
// under the hood, use `getSomeOtherData` method
return this.#someDataService.getSomeOtherData();
}
}
@Component({
// now, provide the adapter instead of the
// `DataService`
providers: [
{
provide: DataService,
useClass: DataServiceAdapter,
}
]
})
export class ParentComponent {}
// and this is it, feel free to call `ReusableComponent`
// in the `ParentComponent` template!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment