Skip to content Skip to sidebar Skip to footer

No Provider For Service Error In Angular2, Why Do I Need To Inject It In It's Parent Component?

I have a pages.service.ts import { Injectable } from '@angular/core'; import { ApiService } from '../../apiService/api.service'; import { Playlists } from '../shared/playlists.mo

Solution 1:

It is a bit strange, but only components can configure dependency injection in Angular (well, and bootstrap()). I.e., only components can specify providers.

Each component in the component tree will get an associated "injector" if the component has a providers array specified. We can think of this like an injector tree, that is (normally much) sparser than the component tree. When a dependency needs to be resolved (by a component OR a service), this injector tree is consulted. The first injector that can satisfy the dependency does so. The injector tree is walked up, toward the root component/injector.

So, in order for your PagesService to inject a ApiService dependency, that ApiService object first has to be registered with an injector. I.e., in a component's providers array. This registration must occur somewhere at or above the component where you want to use/inject the ApiService .

Your service should then be able to inject the registered ApiService object, because it will find it in the injector tree.

See also Angular 2 - Including a provider in a service.

Post a Comment for "No Provider For Service Error In Angular2, Why Do I Need To Inject It In It's Parent Component?"