升级到 Angular 11 后,我无法 ng serve
我的网络应用程序了。
我正在使用 Spring Doc 和最新的 OpenAPI 生成器 gradle-plutin (5.0.0) 生成客户端。
该问题似乎与我的(生成的)REST 客户端有关。打开 https://localhost:4200 会将以下内容写入控制台:
main.ts:12 Error: inject() must be called from an injection context
at injectInjectorOnly (core.js:4901) [angular]
at Module.ɵɵinject (core.js:4911) [angular]
at Object.ApiModule_Factory [as factory] (meditation-rest-client.js:2885) [angular]
at R3Injector.hydrate (core.js:11158) [angular]
at R3Injector.get (core.js:10979) [angular]
at :4200/vendor.js:82591:55 [angular]
at Set.forEach (<anonymous>) [angular]
at R3Injector._resolveInjectorDefTypes (core.js:11016) [angular]
at new NgModuleRef$1 (core.js:25046) [angular]
at NgModuleFactory$1.create (core.js:25100) [angular]
at :4200/vendor.js:100468:45 [angular]
at Object.onInvoke (core.js:28301) [angular]
以下是我的tsconfig.json
文件:/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"module": "es2020",
"lib": [
"es2018",
"dom"
]
}
}
这就是我在 package.json
中定义依赖项的方式 "chart.js": "^2.9.4",
"core-js": "^3.8.2",
"meditation-rest-client": "./generated/meditation-rest-client",
"http-server": "^0.12.3",
"http-status-codes": "^2.1.4",
"moment": "^2.29.1",
这是在上面的错误消息中提到的那些生成的行:// ...
ApiModule.ɵmod = ɵngcc0.ɵɵdefineNgModule({ type: ApiModule });
ApiModule.ɵinj = ɵngcc0.ɵɵdefineInjector({ factory: function ApiModule_Factory(t) { return new (t || ApiModule)(ɵngcc0.ɵɵinject(ApiModule, 12), ɵngcc0.ɵɵinject(ɵngcc1.HttpClient, 8)); }, providers: [], imports: [[]] });
ApiModule.ctorParameters = () => [
{ type: ApiModule, decorators: [{ type: Optional }, { type: SkipSelf }] },
{ type: HttpClient, decorators: [{ type: Optional }] }
];
// ...
这曾经在 Angular 9 中工作,但它不会在 Angular 11 下工作。知道如何解决这个问题吗?我已经尝试过设置
"preserveSymlinks": true
按照建议 here和 here .如果您需要更多信息,请告诉我。
最佳答案
由于生成的 npm 包构建到某些输出文件夹 /generated/meditation-rest-client
中,因此可能会出现此问题。 .
当被前端应用引用时,api 包解析导入 @angular/core
至 /generated/meditation-rest-client/node_modules/@angular/core
,不同于 /node_modules/@angular/core
在项目根目录中。
解决方案是删除 /generated/meditation-rest-client/node_modules
文件夹和 node_modules
父文件夹中,除了 <project-root>/node_modules
.或者,生成的代码 /generated/meditation-rest-client
应该复制到没有父文件夹包含 node_modules
的某个位置文件夹。
见 https://github.com/OpenAPITools/openapi-generator/issues/8447
关于angular - 升级到 Angular 11 后获取 "inject() must be called from an injection context",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65709951/