How to use Angular Decorator to reduce duplicate code?

I have an I18nService that needs to be initialized in 90% of my components. The procedure for this is to import the service, import the translation file, implement the ngOnInit () function, and call the service init().

Now I am trying to reduce duplicate code with Class Decorators. The problem I'm currently facing is using my I18nService inside the decorator, since Decorators seem to work at compile time. I tried to solve the problem with injectors even after this article: https://netbasal.com/inspiration-for-custom-decorators-in-angular-95aeb87f072c but got it AppModule undefined.

How can i solve the problem? Are decorators the right choice to achieve this?

+4
source share
1 answer

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

+3
source

Source: https://habr.com/ru/post/1678720/


All Articles