You can save Injectorin the constructor AppModuleand then use it inside the fixed method ngOnInitto get some service registered in your application
app.module.ts
@NgModule({
...
providers: [AnalyticsService],
})
export class AppModule {
constructor(private injector: Injector) {
AppModule.injector = injector;
}
static injector: Injector;
}
page-track.decorator.ts
import { AnalyticsService, AppModule } from './app.module';
export function PageTrack(): ClassDecorator {
return function ( constructor : any ) {
const ngOnInit = constructor.prototype.ngOnInit;
constructor.prototype.ngOnInit = function ( ...args ) {
let service = AppModule.injector.get(AnalyticsService);
service.visit();
ngOnInit && ngOnInit.apply(this, args);
};
}
}
app.component.ts
@Component({
selector: 'my-app',
templateUrl: `./app.component.html`
})
@PageTrack()
export class AppComponent {}
Plunger example
source
share