简体   繁体   中英

providedin 'root' angular service is undefined

The providedIn property of the Injectable is not working. I have set the provided in property to root but it is undefined when accessed by components through the constructor like so

    public constructor(
    private readonly testService: TestService,
) {}

In the case above, angular throws an error Cannot read properties of undefined (reading 'TestService') .

In the docs the link on providing a service https://angular.io/guide/providers states, after setting providedIn: 'root" that

You can now inject UserService anywhere in your application.

This implies you don't need to do anything else to get access to the service. But in my case I get undefined.

This might somehow be connected to the location of the service in the file hierarchy, as depending on which index.ts file is importing it it will actually be available. But that seems like a bug, since it shouldn't matter where the service is located - it should always be injected in root.

Anyone knows why this is happening?

This error ended up being a red herring for me. The reason the service was undefined all the time was not due to the providedIn field, but rather because I was importing index.ts instead of importing the TestService directly.

For anyone stuck on this issue, make sure you are importing the service directly, even if it is provided in root, because of circular dependency shenanigans, some components can attempt to access your root service too quickly through the index.ts and it just fails.

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