I'm trying to implemnent the scrollOffset method in the Angular router:
@NgModule({
imports: [
RouterModule.forRoot(
routes,
{
anchorScrolling: 'enabled',
scrollPositionRestoration: 'enabled',
scrollOffset: () => {
// TODO: implementation
},
}
)
]
})
export class AppRoutingModule { }
But would like to reference a service here. Does anyone know if theres a way to inject a provider into this method?
I've looked at the Injector but there isn't a static get() so I'm not sure how else to do it.
Thanks
You can't really inject a function. Based on angular DI documentation
Dependencies are services or objects that a class needs to perform its function. DI is a coding pattern in which a class asks for dependencies from external sources rather than creating them itself.
The scrollOffset awaits for either an array [number, number] or a function returning such an array. The function itself can't have a state as an object does, nor can it reference a function from a specific object.
scrollOffset?: [number, number] | (() => [number, number])
You can though declare your functions as a static class member and reference it from there.
Take note that the routes are declared as a const outside of any object, so even if you could reference a specific service function with state and all, there would be no constructor where you can inject this.
declare a injector globally then use it to get your service could work:
import {Injector} from 'angular2/core';
let appInjectorRef: Injector;
export const appInjector = (injector?: Injector):Injector => {
if (injector) {
appInjectorRef = injector;
}
return appInjectorRef;
};
instantiate it in main.ts:
bootstrap(...).then((appRef: ComponentRef) => {
appInjector(appRef.injector); // store a reference to the application injector
});
then use the injector declared in your routing:
scrollOffset: () => {
appInjector().get(YourService)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With