未捕获(在承诺中):TypeError:无法读取 angular 10 中未定义的属性“ɵcmp”
我尝试加载刚刚使用 --prod 标志编译的应用程序时出现此错误
Uncaught (in promise): TypeError: Cannot read property 'ɵcmp' of undefined in angular
,并将optimization和buildOptimizer都设置为true,当我将两者都设置为false时,问题消失,应用程序加载没有问题,但应用程序大小更大,性能不如预期,我需要构建一个生产环境,并将optimization和buildOptimizer都设置为true,有人对这个问题有好的解决办法吗?
angular.json文件:
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
我的.ts代码用于加载动态组件,但在生产 angular 应用程序时,此部分不起作用,并且出现先前的错误:
//Directive created
@ViewChild(RequestsDirective) tabHost: RequestsDirective;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private viewContainerRef: ViewContainerRef,
public requestsMainService: RequestsMainService,
private spinner: NgxSpinnerService) { }
ngOnInit(): void { }
// Load Component in ng template and set request name in services and hide category - request type part
async loadTabComponent(_requestid: number, _requestname: string) {
//debugger;
// to set request name dynamic in all requests
this.requestsMainService.RequestName = _requestname;
// Hide Category And Requests type
$('#div_main').hide('slow');
// Search in App Model about component name
const factories = Array.from(
this.componentFactoryResolver['ngModule']
.instance.constructor.ɵmod.declarations
);
const factoryClass = factories.find(
(x: any) => x.name === ('Request1Component')
) as Type<any>;
// clear any previous component
this.viewContainerRef.detach();
this.viewContainerRef.clear();
// get dynamic component by name
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(factoryClass);
// load it in ng template
this.viewContainerRef = this.tabHost.viewContainerRef;
this.viewContainerRef.createComponent(componentFactory);
}
注意
Request1Component
这个组件名称我想动态加载它
我在 angular 15 上使用 NX 微前端时遇到了此错误,这是因为共享库中的某些组件未从 index.ts 文件中导出。只需检查 index.ts 文件,看看您忘记导出哪个组件。
当您尝试创建/添加/附加 未定义 组件到现有组件引用时,会发生此问题
将此行:
this.viewContainerRef.createComponent(componentFactory);
更改为:
if (factoryClass != undefined) this.viewContainerRef.createComponent(factoryClass);
* 注释 1:
您不再需要对
createComponent()
使用
componentFactoryResolver.resolveComponentFactory()
,它已被弃用,您应该直接将类引用传递给
createComponent()
* 注释 2:
将值传递给
viewContainerRef.createComponent()
时,始终检查它是否为
undefined
,如果不是(可能尚未注册或创建该类)-那么就不要添加它,或者用一些占位符组件替换它
如果您是从Angular Library项目中导入组件,请仔细检查循环依赖项。此错误的一个常见原因是您的项目中具有循环依赖性。