我正在努力为 Angular (v4) 获取 ArcMap Javascript 以在 Angular (v10) 项目中显示 map 。我发现的所有代码示例( here 、 ESRI 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;
map 已绘制,但我不喜欢删除 Typescript 保护,尤其是因为我在网上找到的任何工作示例中都没有这样做。esri-map.component.html 非常简单:
<div #mapViewNode></div>
.如何修复 TS2564 错误?
最佳答案
我的建议是使用可选运算符( ?
)而不是非空断言( !
)。因为属性(property)实际上是undefined
直到组件被渲染,所以,最终你需要潜在地管理 undefined
属性中的值。此外,如果 @ViewChild('compName')
中的组件名称不正确的属性将是 undefined
所以如果你把它标记为可选 听起来比 not-null
更真实选择。
@ViewChild("mapViewNode", { static: true }) private mapViewEl?: ElementRef;
关于angular - TS2564 属性 mapViewEl 没有初始化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63783315/