Home > Enterprise >  How to use a service instead of another service Angular
How to use a service instead of another service Angular

Time:03-18

I have an client application angular who extends another application angular (the source code is in the node modules). The problem is that i have to change some values of variables in a Service call FccGlobalService (the service is in the parent project). In the client appli i have to create a new service ClientFccGlobalService and in this service i import all the content from the FccGlobalService and i have change the values of 3 variables. But when i run the client app angular , the app don't want to use the ClientFccGlobalService but always the FccGlobalService.

Is it possible to tell to my client app to use my service instead of the parent's service ?

here it's my clientAppComponent :

export class ClientAppComponent extends AppComponent implements OnInit {

    constructor(
        public translate: TranslateService, public router: Router, protected commonService: CommonService,
        protected fccGlobalConfiguration: FccGlobalConfiguration, protected checkTimeoutService: CheckTimeoutService,
        protected activatedRoute: ActivatedRoute, protected titleService: Title, protected customHeaderService: CustomHeaderService,
        public dateAdapter: DateAdapter<any>, protected resolverService: ResolverService, protected utilityService: UtilityService,
        protected formControlResolver: FormControlResolverService,
        @Inject(DOCUMENT) public document: any) {
      super(translate, router, commonService, fccGlobalConfiguration, checkTimeoutService,
                activatedRoute, titleService, customHeaderService, dateAdapter, resolverService, utilityService,formControlResolver, document);
    }
}

thanks

CodePudding user response:

What you want is to make use of the Angular Dependency Injection mechanisms. You want for a specific token (FccGlobalService) use a specific value (ClientFccGlobalService). You can do that in the AppModule, which is the highest module in the injection chain, and supply that configuration in the providers array, like below.

@NgModule({
  providers: [
    ...,
    { provide: FccGlobalService, useClass: ClientFccGlobalService }
  ]
})
export class AppModule { }

Basically, what will happen is, whenever someone request an instance of FccGlobalService, what they will get is an instance of ClientFccGlobalService.

  • Related