TS2564属性mapViewEl没有初始化程序

问题描述

我正在努力获取用于Angular(v4)的ArcMap Javascript,以在Angular(v10)项目中显示地图。我发现的所有代码示例(hereESRI Offical here和stackblitz here)都非常相似。 viewChild是这样创建的:

export class EsriMapComponent implements OnInit,OnDestroy {
@ViewChild("mapViewNode",{ static: true }) private mapViewEl: ElementRef;
view: any;
constructor() { }

但是我的IDE通知TS2564 Property mapViewEl has no initializer and is not definitely assigned in the constructor

我可以将此行更改为:

@ViewChild("mapViewNode",{ static: true }) private mapViewEl!: ElementRef;

绘制了地图,但是我不喜欢删除Typescript保护,特别是因为我在网上找到的任何工作示例中都没有这样做。

esri-map.component.html非常简单:<div #mapViewNode></div>

如何解决TS2564错误

解决方法

我的建议是使用可选运算符 (?) 而不是非空断言 (!)。因为在呈现组件之前,该属性实际上是 undefined,因此,最终您需要管理该属性中可能存在的 undefined 值。此外,如果 @ViewChild('compName') 中的组件名称不正确,则属性将为 undefined,因此如果您将其标记为可选,这听起来比 not-null 替代方案更现实。

@ViewChild("mapViewNode",{ static: true }) private mapViewEl?: ElementRef;