繁体   English   中英

如果密钥存在于 angular 5 html 中,则显示 map 值

[英]display the map value if key exists in angular 5 html

component文件中创建了 map - tempDAMap

import 'rxjs/add/operator/map';
export class AComponent implements OnInit {
  tempDAMap = new Map();
    /** Onchange */
  selectedName(pName: any): void {
    this.service.getPAData(pName).subscribe( (data) => {
      if (data.length > 0 && data != '' && data != null) {
    this.savedData = data;
    this.tempDataStatus = true;
    this.savedData.forEach(function(assessData) {
      this.tempDAMap.set(assessData.qId, assessData.ansSelected);
    })
      }
      else {
        this.tempDataStatus = false;
      }
    },
    (error) => {} )
  }
}

在 HTML 文件中,有一个包含QuestionId的外部 for 循环,并在 map(子集)内检查QuestionId是否存在于其中并显示来自 map tempDAMap的值。

    <div *ngFor="let QA of Questions">
      <div>  <label> {{ques.desc}} </label>
        <div *ngIf="tempDataStatus === true">
 /** Check if tempDAMap contains Id (from Questions- outer for loop)*/
        <div *ngIf="tempDAMap.has(ques.questionId)"> 
          <p> {{ }} </p>  /** display the map value  */
        </div>
        </div>
      </div>
    </div>

我无法检查密钥是否存在并显示 map 值。

错误:TypeError:无法读取未定义的属性“tempDAMap”。

请帮我。

代替:

this.savedData.forEach(function(assessData) {
 this.tempDAMap.set(assessData.qId, assessData.ansSelected);
});

您需要使用箭头功能:

this.savedData.forEach((assessData) => {
  this.tempDAMap.set(assessData.qId, assessData.ansSelected);
});

In javascript, function is a keyword that represents an action but it also has similar behavior to the class keyword , playing the role of a class constructor when it appears after another keyword: new (eg. new function(...) {...} )。 最初这甚至是在 javascript 中实例化对象的方式。

Because of that, when you use the function keyword you set a scope, and the this inside it refers to the function itself, as a consequence of its class constructor behavior.

可以通过以下两种方式之一避免上述行为:

  1. 老派:将外部 scope 保存在临时变量中,以便可以在 function 内部使用( that是用于此任务的通用变量名称):
const that = this;
this.savedData.forEach(function(assessData) {
 that.tempDAMap.set(assessData.qId, assessData.ansSelected);
});
  1. 箭头函数:为避免在 function 中捕获this的含义,您可以在创建 function 时避免使用function关键字。 取而代之的是,您可以使用箭头 function表示法(其他编程语言中的lambda 函数)来定义您的函数。 By doing that the this keyword inside the body of the arrow function will refer to the outside scope (some people like to say that you bring the outside scope to the function scope ).

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM