Home > OS >  Unable to inject dependency in resolved service
Unable to inject dependency in resolved service

Time:09-23

I've came across this specfic problem in my Angular project architecture:

I have one component that need to load different service depending on current URL. It's done by resolving service like in example below.

ChartRoutingModule

const routes: Routes = [
    {
        path: 'doctorspecialities',
        component: ChartComponent,
        resolve: {
            service: DoctorSpecialitiesServiceResolver,
        },
    },
]
@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule],
    providers: [DoctorSpecialitiesServiceResolver],
})
export class ChartRoutingModule {}

When user enter specific url the service is resolved:

DoctorSpecialitiesServiceResolver

@Injectable()
export class DoctorSpecialitiesServiceResolver implements Resolve<any> {
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        return new DoctorSpecialitiesService();
    }
}

And the service is in ActivatedRoute. Everything works fine for now. But I need to inject HttpClient into this service. Adding private _http: HttpClient in constructor of DoctorSpecialitiesService results in this error:

An argument for '_http' was not provided.

I think I should pass this dependency in Resolver but I have no idea where should I declare it. Couldn't find anything that helps me. Could you give me a hand with this?

CodePudding user response:

You can have the HttpClient injected in your resolver, then pass that to the DoctorSpecialitiesService constructor like so:

@Injectable()
export class DoctorSpecialitiesServiceResolver implements Resolve<any> {
    constructor(private http: HttpClient) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        return new DoctorSpecialitiesService(this.http);
    }
}
  • Related