Inject different services depending on the URL parameter in angular

Viewed 82

I would like to inject different Service depending on URL parameter.

@Injectable({
  providedIn: 'root'
})
export class SomeService {
     :
}

@Injectable({
  providedIn: 'root'
})
export class AService extends SomeService {
     :
}

@Injectable({
  providedIn: 'root'
})
export class BService extends SomeService {
     :
}


@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  private param = this.activatedRoute.snapshot.queryParams.someParam === 'someValue';

  constructor(
    private activatedRoute: ActivatedRoute,
    private someService: SomeService,   // when param is true, use AService. when false, use BService.
  ) { }

  ngOnInit(): void {
  }

}

When called this component with URL parameter someParam=someValue, I would like to use AService. Otherwise I would like to use BService.

How Can I do this?

1 Answers

Hi Here you can make a use of provide with useFactory approach.

Here is how your providers section will look a like in your module.

@NgModule({ 
 declarations:[],
 providers:[
     {
       provide: SomeService,
       useFactory: (activatedRoute: ActivatedRoute, injector:Injector) => {
             let param = this.activatedRoute.snapshot.queryParams.someParam;
             if(param === 'somevalue'){
                return injector.get(AService);
             }else {
                 return injector.get(BService);
             }
       },
       deps:[ActivatedRoute, Injector]
     }
 ]
})
Related