Search code examples
angulardependency-injectionangular-services

Passing parameter to Service injected into another Service


I have a service ApiClientService which is injected in other Services and Components across my application. For instance it is injected in the TestService below.

My ApiClientService has a parameter baseUrl that can change at injection time

How can I provide the value when injecting it in TestService ?

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

  constructor(private apiClient: ApiClientService) { }
}


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

   constructor( @Inject('baseUrl') private baseUrl: string) {
   }

}

Solution

  • I found out how to do it, the trick was to create an InjectionToken and provide it at module level.

    export const API_CLIENT_SERVICE_BASE_URL = new InjectionToken<string> ('ApiClientServiceBaseUrl');
    
      @Injectable({ providedIn: 'root' })
      export class ApiClientService {
    
      public baseUrl: string;
    
       constructor() {
          this.baseUrl = inject(API_CLIENT_SERVICE_BASE_URL);
       }
    
    }
    

    and in my module :

    providers: [
        {
          provide: API_CLIENT_SERVICE_BASE_URL,
          useValue: 'some value'
        }
      ]
    

    Now in TestService, the value of apiClient.baseUrl is 'some value'.