Reputation: 378
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?
Upvotes: 0
Views: 1987
Reputation: 378
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.
Upvotes: 4