你可以存儲在構造AppModule
Injector
,然後用它裏面打補丁ngOnInit
方法得到一些服務在您的應用程序註冊
app.module.ts
@NgModule({
...
providers: [AnalyticsService],
})
export class AppModule {
constructor(private injector: Injector) {
AppModule.injector = injector;
}
static injector: Injector;
}
頁軌道。 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 {}
Plunker Example
謝謝,我知道了你的代碼的工作:) – dtrinh