严格模式 - 使用 lazy-loaded 组件将值设置为 ngComponentOutlet 时类型不兼容
Strict mode - type incompatibility when setting value to ngComponentOutlet with lazy-loaded component
我正在尝试 lazy-load Angular 11(严格模式)中的组件 this guide。严格模式一直很痛苦,因为几乎没有 examples/tutorials 使用它。
此组件将加载适当的 header 组件(最终)。我只是想 lazy-load 一个用于“站点 A”的启动。
header-loader-component.ts
@Component({
selector: 'header-loader',
template: `<ng-template [ngComponentOutlet]="headerComponent | async"></ng-template>`,
styles: []
})
export class HeaderLoaderComponent implements OnInit {
headerComponent: Promise<Type<SiteAHeaderComponent>>;
constructor() { }
ngOnInit(): void {
this.LoadHeaderComponent();
}
private LoadHeaderComponent() {
if (!this.headerComponent) {
this.headerComponent = import(`../myFolder/siteA-header/siteA-header.component`)
.then(({ SiteAHeaderComponent}) => SiteAHeaderComponent);
}
}
}
有了这个,我得到错误:
Property 'headerComponent' has no initializer and is not definitely
assigned in the constructor.
好的,我现在已经习惯了严格模式下的那个错误,所以我把它改成:
headerComponent: Promise<Type<SiteAHeaderComponent>> | null = null;
因此它可以在 ngOnInit 有机会设置它之前开始 null。
现在 [ngComponentOutlet]
我得到:
Type 'Type | null' is not assignable to type
'Type'
如何设置 headerComponent
的值?
编辑:
可以肯定的是,我只是在 Strict 暂时禁用的情况下尝试了这个并且效果很好。
分配时使用 !
符号和 属性,例如 headerComponent!
.
带有 属性 名称的 !
符号表示您明确声明 - “我知道这个 属性 有一个非空值”。在你的情况下,如果它有一个非空值,那么它的值肯定是 Type
.
类型
编辑:
由于 属性 headerComponent
是 Promise
类型,因此您必须使用 !
符号括起模板中的 async
管道,例如 (headerComponent|async)!
。
此外,我建议使用 -
headerComponent: Promise<Type<any>> | null = null;
否则以后将无法通过headerComponent
属性.
设置不同类型的header组件
我正在尝试 lazy-load Angular 11(严格模式)中的组件 this guide。严格模式一直很痛苦,因为几乎没有 examples/tutorials 使用它。
此组件将加载适当的 header 组件(最终)。我只是想 lazy-load 一个用于“站点 A”的启动。
header-loader-component.ts
@Component({
selector: 'header-loader',
template: `<ng-template [ngComponentOutlet]="headerComponent | async"></ng-template>`,
styles: []
})
export class HeaderLoaderComponent implements OnInit {
headerComponent: Promise<Type<SiteAHeaderComponent>>;
constructor() { }
ngOnInit(): void {
this.LoadHeaderComponent();
}
private LoadHeaderComponent() {
if (!this.headerComponent) {
this.headerComponent = import(`../myFolder/siteA-header/siteA-header.component`)
.then(({ SiteAHeaderComponent}) => SiteAHeaderComponent);
}
}
}
有了这个,我得到错误:
Property 'headerComponent' has no initializer and is not definitely assigned in the constructor.
好的,我现在已经习惯了严格模式下的那个错误,所以我把它改成:
headerComponent: Promise<Type<SiteAHeaderComponent>> | null = null;
因此它可以在 ngOnInit 有机会设置它之前开始 null。
现在 [ngComponentOutlet]
我得到:
Type 'Type | null' is not assignable to type 'Type'
如何设置 headerComponent
的值?
编辑:
可以肯定的是,我只是在 Strict 暂时禁用的情况下尝试了这个并且效果很好。
分配时使用 !
符号和 属性,例如 headerComponent!
.
带有 属性 名称的 !
符号表示您明确声明 - “我知道这个 属性 有一个非空值”。在你的情况下,如果它有一个非空值,那么它的值肯定是 Type
.
编辑:
由于 属性 headerComponent
是 Promise
类型,因此您必须使用 !
符号括起模板中的 async
管道,例如 (headerComponent|async)!
。
此外,我建议使用 -
headerComponent: Promise<Type<any>> | null = null;
否则以后将无法通过headerComponent
属性.