Angular组件初始化Map对象报错:this.hotKeys未定义
问题原因
你遇到的错误是因为hotKeys变量仅声明了类型,但没有实例化Map对象,此时this.hotKeys的值是undefined,调用set方法自然会报错。这和bind函数无关,你找错了解决方向。
解决方案
有三种常见的修正方式,任选其一即可:
方式1:声明时直接实例化
在变量声明时就创建Map实例,之后在构造函数中调用set方法:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-hint-for-hotkeys', templateUrl: './hint-for-hotkeys.component.html', styleUrls: ['./hint-for-hotkeys.component.css'] }) export class HintForHotkeysComponent implements OnInit { // 声明时直接实例化Map hotKeys: Map<string, string> = new Map(); keys: any; values: any; constructor() { this.hotKeys.set("Alt+N", " - to create a node. (only on page for nodes)"); this.hotKeys.set("Alt+L", " - to create a link. (only on page for links)"); this.hotKeys.set("Alt+F", " - to create the field for creating the new property of the link or node."); this.hotKeys.set("Alt+S", " - to save a node/a link or changes in it."); this.hotKeys.set("Alt+D", " - to delete the field for creating the new property of the link or node. Be sure that you're focused on field you want to delete."); this.hotKeys.set("Alt+R", " - to delete a node or a link."); this.hotKeys.set("🠔 and ➝", " - a transition between web-pages."); this.hotKeys.set("↑ and 🠗", " - a switching between nodes or links."); this.hotKeys.set("Esc", " - to go to main page."); this.keys = this.hotKeys.keys(); this.values = this.hotKeys.values(); } ngOnInit(): void { } }
方式2:构造函数内先实例化再赋值
先在构造函数中创建Map实例,再调用set方法:
constructor() { // 先实例化Map this.hotKeys = new Map(); // 再执行set操作 this.hotKeys.set("Alt+N", " - to create a node. (only on page for nodes)"); // 其他set语句... this.keys = this.hotKeys.keys(); this.values = this.hotKeys.values(); }
方式3:直接通过Map构造函数初始化所有键值对
这种方式更简洁,一次性完成实例化和赋值:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-hint-for-hotkeys', templateUrl: './hint-for-hotkeys.component.html', styleUrls: ['./hint-for-hotkeys.component.css'] }) export class HintForHotkeysComponent implements OnInit { // 直接用键值对数组初始化Map hotKeys: Map<string, string> = new Map([ ["Alt+N", " - to create a node. (only on page for nodes)"], ["Alt+L", " - to create a link. (only on page for links)"], ["Alt+F", " - to create the field for creating the new property of the link or node."], ["Alt+S", " - to save a node/a link or changes in it."], ["Alt+D", " - to delete the field for creating the new property of the link or node. Be sure that you're focused on field you want to delete."], ["Alt+R", " - to delete a node or a link."], ["🠔 and ➝", " - a transition between web-pages."], ["↑ and 🠗", " - a switching between nodes or links."], ["Esc", " - to go to main page."] ]); keys: any; values: any; constructor() { this.keys = this.hotKeys.keys(); this.values = this.hotKeys.values(); } ngOnInit(): void { } }
补充说明
bind函数用于修正函数的this指向,但你的问题根源是变量未初始化,所以用bind无法解决。只要确保hotKeys在调用set方法前已经被实例化为Map对象,错误就会消失。
内容的提问来源于stack exchange,提问作者Denis Bredun
相关产品推荐
相关产品推荐

