简体   繁体   中英

"Error: inject() must be called from an injection context" with npm link, Angular and library with peerDependencies

I have an application MyApp and a library MyLib. MyApp consumes MyLib. We package and bundle MyLib on Azure Devops as an Artifact, that can be consumed both on Azure and locally. This all works fine. However, I want to work on both MyApp and MyLib locally, so I wanted to try npm link. I link to the dist-folder of MyLib, as that is the same form MyApp normally consumes MyLib. This works, I can see that the linked version is used and the package is added to the global npm packages. MyApp will also compile, but it will not run. In the console I see the error:

vendor.js:18783 ERROR Error: inject() must be called from an injection context
    at injectInjectorOnly (vendor.js:108835:11)
    at Object.ɵɵinject (vendor.js:108844:59)
    at Object.LanguageService_Factory [as factory] (main.js:2377:96)
    at R3Injector.hydrate (vendor.js:24776:29)
    at R3Injector.get (vendor.js:24576:23)
    at NgModuleRef$1.get (vendor.js:41158:29)
    at Object.get (vendor.js:40822:29)
    at lookupTokenUsingModuleInjector (vendor.js:15125:31)
    at getOrCreateInjectable (vendor.js:15244:10)
    at Object.ɵɵdirectiveInject (vendor.js:28568:10)

This LanguageService is part of the library, it is a service with "providedIn: root". I first thought that something was wrong with peerDependencies and I have also tried to make a custom webpack file and provide aliases, but this issue persists. So I might be on the wrong track. What am I missing?

I was having a similar issue regarding the npm link.

Solved it by adding the configuration "preserveSymlinks": true to the angular.json file in the main project:

{
  "projects": {        
    "architect": {
      "build": {
          ...,
          "preserveSymlinks": true
        },

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