Search code examples
angulartypescriptservice

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


Solution

  • 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