Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular - providing different services for modules

i have a problem with providing different services to modules.

I have three modules: ModuleA, ModuleB and ModuleShared. I want ModuleA and B to provide to ModuleShared different service using Injectin Token. I am trying to do this, but as You can see, components from module A and B are using only service B. How to provide to shared module different services ?

--- edit ---

ModuleA:

@Injectable()
export class ServiceA implements IMyService {
  getName(): string {
    return 'service A';
  }
}

@Component({
  selector: 'component-a',
  template: `
    <div>
      Cpomonent from Module A:
      <shared-component></shared-component>
    </div>
  `,
})
export class ComponentA {

}

@NgModule({
  imports: [
    ModuleShared
  ],
  declarations: [
    ComponentA
  ],
  exports: [
    ComponentA
  ],
  providers: [
    {
      provide: MY_SERVICE,
      useClass: ServiceA
    }
  ]
})
export class ModuleA {}

ModuleB:

@Injectable()
export class ServiceB implements IMyService {
  getName(): string {
    return 'service B';
  }
}

@Component({
  selector: 'component-b',
  template: `
    <div>
      Component from Module B:
      <shared-component></shared-component>
    </div>
  `,
})
export class ComponentB {

}
@NgModule({
  imports: [
    ModuleShared
  ],
  declarations: [
    ComponentB
  ],
  exports: [
    ComponentB
  ],
  providers: [
    {
      provide: MY_SERVICE,
      useClass: ServiceB
    }
  ]
})
export class ModuleB {}

SharedModule:

export interface IMyService {
  getName: string
};
export const MY_SERVICE = new InjectionToken<IMyService>('MyService');


@Component({
  selector: 'shared-component',
  template: `
    <div>
      <h3>Shared component, provided: {{serviceName}}</h3>
    </div>
  `,
})
export class ComponentShared {

  constructor(@Inject(MY_SERVICE) private myService: IMyService) {}

  get serviceName(): string {
    return this.myService.getName();
  }
}

@NgModule({
  declarations: [
    ComponentShared
  ],
  exports: [
    ComponentShared
  ]
})
export class ModuleShared {}

https://plnkr.co/edit/Lbr23I4wC2A0HruvMU6m?p=preview

like image 535
KrzysztofO Avatar asked Mar 01 '26 15:03

KrzysztofO


1 Answers

This can only work if ModuleA and ModuleB are lazy loaded modules,
otherwise they all share the same provider scope and subsequently registered providers with the same key (MY_SERVICE) will override the previously registered one.

Lazy-loaded modules introduce a new sub-scope and therefore can provide different providers which won't override each other.

like image 98
Günter Zöchbauer Avatar answered Mar 03 '26 05:03

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!