Angular 11 Inject URL into service

728 views Asked by At

I have 2 layers of services and would like to refactor them using Angular (version 11) Injection.

  1. A base service, which makes calls to a backend and has bunch of logic on how to handle data and security. Here is constructor:
  constructor(url: string, httpClient: HttpClient) {
    this.url = url;
    this.client = new HttpClientWrapper(httpClient);
  }
  1. Specific services, that are basically configure new base service and delegate all the calls from component to the base service:
  private baseService: BaseService;

  constructor(public httpClient: HttpClient) {
    const url = environment.baseUrl + 'somePath';
    this.baseService = new BaseService(url, httpClient);
  }

Question: since each specific service doesn't really do much, how can injection be employed to refactor above setup?

1

There are 1 answers

0
Kavinda Senarathne On

On the parent module create a provider for API_BASE_URL

export function getBaseUrl(): string {
  return AppConsts.baseUrl;
}

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [{ provide: API_BASE_URL, useFactory: getBaseUrl }],
   bootstrap: [AppComponent]
})
export class AppModule {}

and then define a AppConsts class with static properties as such

export class AppConsts {
  static baseUrl = "your_api_base_url"; 
}