How to provide two classes in Angular DI

183 views Asked by At

I have two adapter classes that both extend from the same class, something like this:

NativeDateAdapter extends DateAdapter;

MaterialJalaliDateAdapter extends DateAdapter;

I want to provide both of them in my service so try these ways but got errors.

  @NgModule({
       providers: [
         {
           provide: DateAdapter,
           useClass: MaterialJalaliDateAdapter,
           multi: true,
           deps: [MAT_DATE_LOCALE],
         },
         { provide: DateAdapter, useClass: NativeDateAdapter, multi: true, deps: [MAT_DATE_LOCALE] 
         }
       ]
    })

myService.ts: (This is what I need)

 constructor(@Inject(DateAdapter) private dateAdapters: DateAdapter<any>[]){
    if (this.calendarType == 'A') {
        this.dateAdapter = dateAdapters[1];
    } else {
        this.dateAdapter = dateAdapters[0];
    }
 }

the error for this way is:

enter image description here

also, try this way but got the error:

@NgModule({
  providers: [
    {
      provide: DateAdapter,
      useValue: [NativeDateAdapter, MaterialJalaliDateAdapter],
      deps: [MAT_DATE_LOCALE],
    },
  ]
})
1

There are 1 answers

2
Ivan Tarskich On

Providing 2 classes under the same name is not possible. You could set an Alias

@NgModule({
       providers: [
         {
           provide: DateAdapterMJDA,
           useClass: MaterialJalaliDateAdapter,
           multi: true,
           deps: [MAT_DATE_LOCALE],
         },
         { provide: DateAdapterNDA, useClass: NativeDateAdapter, multi: true, deps: [MAT_DATE_LOCALE] 
         }
       ]
    })

 constructor(@Inject(DateAdapterMJDA) private dateAdaptersMJDA: DateAdapter<any>[], @Inject(DateAdapterNDA) private dateAdaptersNDA: DateAdapter<any>[]){
if (this.calendarType == 'A') {
    this.dateAdapter = dateAdaptersMJDA;
} else {
    this.dateAdapter = dateAdaptersNDA;
}

}