Angular 6 service with interface

前端 未结 4 1297
旧时难觅i
旧时难觅i 2021-01-02 04:00

I am building an application with Angular (6.0.7) and I am trying to create a service with the new:

@Injectable({
  providedIn: \'root\'
})
         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 04:27

    I used something like the following to solve this

    app.module.ts

    providers: [
      { provide: AlmostInterface, useClass: environment.concrete }
      ...
    ]
    

    AlmostInterface.ts

    export abstract class AlmostInterface {
       abstract myMethod();
    }
    

    MyConcrete.ts

    export class MyConcrete implements AlmostInterface {
       myMethod() { ... }; // implementation
    }
    
    export class MyConcreteAlternative implements AlmostInterface {
       myMethod() { ... }; // implementation
    }
    

    environment.ts

    export const environment = {
      production: false,
      concrete: MyConcreteAlternative
    };
    

    environment.prod.ts

    export const environment = {
      production: true,
      concrete: MyConcrete
    };
    

提交回复
热议问题