jeudi 12 août 2021

Creating a type using Abstract Class Service and using it with useClass - Angular

I have been able to create a working application. But I am getting an error when I am using the abstract class (ClientService) as type and then using it with useClass.

Before I start, let me explain the design.

  1. app.module is the main app module.

  2. I have a dynamic module (external.module.ts) that can be configured dynamically to show different types of planet dashboards.

  3. I have created mars-dashboard.module which basically wraps external.module.ts inside it and sends the configuration for external.module.ts to work accordingly.

  4. I have created an abstract class (inside external.module) ClientService which has some methods as abstract . It is upto the mars-dashboard.module to decide what payload should be prepared for Mars planet for those respective methods. This is achieved by extending it to MyAppClientService

  5. There can be some methods which have same response across Planets, therefore they are implemented in our abstract class. They are just for display purpose.

Here is the demo code

Everything works as expected. The problem comes when I set the type of ClientService in external.module.ts:

external.module.ts

export class ExternalModule {
  static forRoot<T>(config: {
    name: string;
    clientService: any; //TODO: add type which creates problem
  }): ModuleWithProviders<ExternalModule> {
    return {
      ngModule: ExternalModule,
      providers: [
        {
          provide: CLIENT_SERVICE,
          useClass: config.clientService  // useClass does not accept abstract class
        },
        {
          provide: DASHBOARD_NAME,
          useValue: config.name
        }
      ]
    };
  }
}

Question:

  1. How should I design this so that the angular type also approves my implementation.

  2. Is there a better way to solve this design challange?

Please note, in actual implementation, the external.module is a separate lib which I have created using Nx

Aucun commentaire:

Enregistrer un commentaire