1

I am trying to update the useClass based on the condition. When I am trying to change the tab I want to update the service. So I wrote one factory function for that.

let useClassFactory = ( conn: service1, svc: service2, object: any ) => { let path = typeof object == 'string' ? object : object?.path if (path === 'connections') { return conn } else if (path === 'services') { return svc } else { return conn } } @Component({ selector: 'cmpnt-form', templateUrl: './cmpnt-form.component.html', changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: QPService, // useClass: SvcService, useFactory: useClassFactory, deps: [ConnService, SvcService] }, { provide: TableService, useClass: TableService, deps: [QPService] } ] }) onTabClick(path: any) { useClassFactory(this.ConnService, this.svcService, path) this.getColumns(path).subscribe({ next: (data: ModelAsTableColumns[]) => { this.columns = data this.dataSource = [] }, error: (err) => {} }) } 

Factory function is working and returning proper service based on the path. But when I am hitting the API it's going to the default service only. Do I have to update anything after factory fucntion?

I tried to use the different services inside the useClass based on the tab click. But it's hitting the same API.

2 Answers 2

0

Why do you need a factory for this, a simple getter method will be enough right?

get conditionalService() { return this.path === 'connections' ? this.ConnService : this.svcService; } 

Then you can use it like so

(this.conditionalService as ConnectionService).getColumns(); 
Sign up to request clarification or add additional context in comments.

6 Comments

No. I want the useClass should be changed based on the condition. That's why I wrote the factory function.
Hope you understand my question @Naren Murali
@Saravanan You cannot reinitialize the provider as far as I know stackblitz what you have asked in the question is the equivalent of what I have answered!
Ok. Thanks. What about the dynamic imports?
@Saravanan please include the details on the question, maybe someone will answer!, I am not familiar with dynamic imports
|
0

Indeed, services cannot be reinitialized after the component has rendered. I've discovered an alternative solution. I'm utilizing child components dedicated to specific services and dynamically rendering them based on the selected tab.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.