How to update the useClass in providers based on the condition in Angular

105 views Asked by At

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

There are 2 answers

6
Naren Murali On

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();
0
Saravanan On

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.