【问题标题】:How to use Angular Decorator to reduce repetitive code?如何使用 Angular Decorator 减少重复代码?
【发布时间】:2017-11-09 01:44:33
【问题描述】:
【问题讨论】:
标签:
javascript
angular
typescript
service
decorator
【解决方案1】:
您可以将Injector 存储在构造函数AppModule 中,然后在修补的ngOnInit 方法中使用它来获取在您的应用中注册的一些服务
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 {}
Plunker Example