如何使用 Angular Decorator 减少重复代码?

dtr*_*inh 5 javascript service decorator typescript angular

我有一个 I18nService 需要在我的 90% 的组件中初始化。执行此操作的过程是导入服务、导入翻译文件、实现 ngOnInit() 和调用服务init()函数。

现在我试图在类装饰器的帮助下减少重复代码。我目前面临的问题是在装饰器中使用我的 I18nService,因为装饰器似乎在编译时运行。我试图用注射器解决这个问题,并按照这篇文章:https : //netbasal.com/inspiration-for-custom-decorators-in-angular-95aeb87f072c 但得到了AppModule undefined.

我该如何解决问题?装饰器是实现这一目标的正确选择吗?

yur*_*zui 5

您可以存储Injector在构造函数中AppModule,然后在修补ngOnInit方法中使用它来在您的应用程序中注册一些服务

app.module.ts

@NgModule({
  ...
  providers: [AnalyticsService],
})
export class AppModule {
  constructor(private injector: Injector) {
    AppModule.injector = injector;
  }

  static injector: Injector;
}
Run Code Online (Sandbox Code Playgroud)

页面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);
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: `./app.component.html`
})
@PageTrack()
export class AppComponent {}
Run Code Online (Sandbox Code Playgroud)

Plunker 示例