gpt4 book ai didi

Angular 升级 - 错误 : inject() must be called from an injection context at injectInjectorOnly

转载 作者:行者123 更新时间:2023-12-05 03:37:41 25 4
gpt4 key购买 nike

我有一个结构如下的 Angular 项目:

站点 1

  • 模块 1
  • 模块 2
  • SharedModule <- 不在库中,只是一个模块

站点 2

  • 模块 3
  • 模块 4
  • SharedModule <- 直接调用 Main 中的模块

我知道这并不理想,但事实就是如此。

除了应用程序的名称外,package.json 文件完全相同。

该项目是在 Angular 8 上启动的,并且一直升级良好,但是从 11 -> 12 开始我遇到了问题:

站点 1 构建良好且运行良好。 Site2 构建良好,但运行时立即出错

Error: inject() must be called from an injection contextat injectInjectorOnly (core:4745)at Module.ɵɵinject (core:4755)at Object.RouterModule_Factory [as factory] (router:5999)at R3Injector.hydrate (core.js:11438)at R3Injector.get (core.js:11257)at core.js:11295at Set.forEach ()at R3Injector._resolveInjectorDefTypes (core.js:11295)at new NgModuleRef$1 (core.js:25325)at NgModuleFactory$1.create (core.js:25379)

由于 Site1 工作正常,我想它一定是在调用那个 SharedModule?

我试过将 "preserveSymlinks": true, 添加到 projects.$name.architect.build.options,但这不起作用。我没有使用 npm link,因为另一个模块不是库(我知道应该这样设置,但事实并非如此)。

我至少花了 2 天的时间试图让它工作(显然检查了 thisthis 等帖子,但那里的答案似乎不起作用。

有谁知道如何解决这个问题,或者至少知道如何调试它?

最佳答案

为了搜索者的利益,在这里没有得到回应,我问了this到 Angular 本身。

这里是提供的答案。

You have two distinct workspace trees that import from eachother. That is bound to suffer from duplicate @angular/core versionswhich confuses the runtime, resulting in the rather obscure runtimeerror you're seeing. You can workaround this using paths mappings, asexplained in the library guide here (which also applies to yoursituation without libs). Not sure why it worked in earlier versions,it has always been prone to these kinds of issues.

The cause is that the two separate workspaces both have their own@angular/core packages, and both end up in the bundled application.The Angular runtime keeps its state in top-level module variables thatare private to that module, but having two occurrences of that module(from both instances of @angular/core) you run into situations wherestate is only initialized correctly in one instance, not the other. Inthis case the injection context is only available in the "primary"runtime, but the parts of the app that were bundled from the"secondary" library parts will depend on the "secondary" runtimestate.

所以基本上,结构不好。它应该首先作为一个适当的图书馆项目来完成。

我已经制作了一个应该如何完成的演示 here .

关于 Angular 升级 - 错误 : inject() must be called from an injection context at injectInjectorOnly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69212072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com