I'm creating a library in angular, which uses HttpClient and I need to inject the baseUrl to use.
this is what I have in the library:
//service
export class ApiService {
constructor(
private readonly httpClient: HttpClient,
@Inject('baseUrl') private baseUrl: string) {
}
get<T>(resource: string, options?: object): Observable<T> {
return this.httpClient.get<T>(`${this.baseUrl}${resource}`, options);
}
}
// Module
@NgModule({
imports: [
CommonModule
],
providers: [
ApiService
]
})
export class NxServicesModule {
public static forRoot(baseUrl: string): ModuleWithProviders<NxServicesModule> {
return {
ngModule: NxServicesModule,
providers: [
{
provide: ApiService,
useValue: baseUrl
}
]
};
}
}
Then I try to use it in my application, this is my module1.module
@NgModule({
declarations: [
MyComponent
],
imports: [
],
exports: [
],
providers: [
ApiService.forRoot({baseUrl: environment.baseUrl})
]
})
It raises an error when compiling:
Property 'forRoot' does not exist on type 'typeof ApiService'.
What am I doing wrong?
The problem is that forRoot
is declared in your NxServicesModule
not in your ApiService
. Also you should pass a string
not an object, or you should change the argument of the forRoot
method accordingly.
Note: Doesn't your IDE catch these things? And the compiler should also log errors for these things I would say. Maybe you should check your configuration?
Some clarification after your comment. You need to change as follows:
@NgModule({
declarations: [
MyComponent
],
imports: [
NxServicesModule.forRoot(environment.baseUrl)
]
})