简体   繁体   中英

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

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

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<\/a> ) demo: https:\/\/stackblitz.com\/edit\/angular-ivy-e4onjc?file=src\/app\/app.component.ts<\/a>

"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM