Nana Ba
Nana Ba

Reputation: 87

How to inject service into an another service with Angular 6/7 ? (providedIn: 'root') Service is always undefined

Service stays undefined when it injects into an another using providedIn: "root"

I've tried to put in module and/or component: providers: [service1, service2] and remove providedIn: "root", but it still not working.

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

    @Injectable({
        providedIn: 'root'
    })
    export class Service2 {
        constructor(private service1: Service1) {
            console.log(service1) // undefined
        }
     }

     export class Component {
         constructor(private service2: Service2) {}
     }

service 1 is always undefined

Upvotes: 0

Views: 2244

Answers (2)

Valentin Bossi
Valentin Bossi

Reputation: 305

The services are provided in root it does not "depend" cause they both are "defined" in root, thus there is no before or after. Angular just creates the service-to-be-injected first otherwise angulars DI would not work. Its in general recommended providing services in the root scope. "You should always provide your service in the root injector unless there is a case where you want the service to be available only if the consumer imports a particular @NgModule." (https://angular.io/guide/providers#provider-scope) demo: https://stackblitz.com/edit/angular-ivy-e4onjc?file=src/app/app.component.ts

Upvotes: 0

Ankii32
Ankii32

Reputation: 106

This is a nice question, answer to this is :

It depends on the order of execution

If you define your service2 before service1 it will throw error, so order matters

Code Snippet

Response

Upvotes: 4

Related Questions