简体   繁体   English

Angular Typescript - Map.get 返回未定义,尽管地图包含 7 个值

[英]Angular Typescript - Map.get returns undefined, although the map contains 7 values

Map.get always returns undefined when using number from form element (extra1):使用表单元素(extra1)中的数字时,Map.get 总是返回 undefined:

  extraById = new Map<number,Extra>();
  @Input() extra1: number = -1;

  formChanged(carConfigurationFormChanged : any) {
    const index = this.extra1;
    const record : Extra | undefined = this.extraById.get(index);
    this.gesamtpreis = "" + record?.preis?.toString() + " " + Math.random().toString();//909 0.784784
  }

I will provide an answer to this question myself.我将自己提供这个问题的答案。 The template:模板:

<div class="card my-5">
  <div class="card-body">
    <form #carConfigurationForm="ngForm"  (change)="formChanged(carConfigurationForm)">
      <div class="form-group">
        <label for="extra">Extra 1&nbsp;</label>
        <select name="extra1" class="btn btn-secondary dropdown-toggle" [(ngModel)]="extra1">
          <option value="default">Kein Extra</option>
          <option *ngFor="let extra of selectExtra" [value]="extra.id">{{extra.name}} {{extra.preis}}&euro;</option>
        </select>
      </div>
        <div class="form-group">
          <label for="gesamtpreis">Gesamt&nbsp;</label>
          <span name="gesamtpreis" [innerHTML]="gesamtpreis" ngModel="gesamtpreis"></span>
        </div>
    </form>
  </div>
</div>

One solution is to use Math.trunc on the value from the form:一种解决方案是对表单中的值使用Math.trunc

import { Component, OnInit, OnChanges, Input } from '@angular/core';
import { Extra } from '../model/extra';
import { ExtraService} from '../service/extra.service';

@Component({
  selector: 'app-car-configuration-form',
  templateUrl: './car-configuration-form.component.html',
  styleUrls: ['./car-configuration-form.component.sass']
})
export class CarConfigurationFormComponent implements OnInit{

  selectExtra : Extra[] = [];

  gesamtpreis : string = 'kein Preis';

  extraById = new Map<number,Extra>();

  constructor(private extraService: ExtraService) { }

  getSelectedExtra(): void{
    this.extraService.findAll()
      .subscribe(selectExtra => {
        this.selectExtra= selectExtra;
        this.selectExtra.forEach( (record : Extra)  => { this.extraById.set(record.id, record); });
        }
     );
  }

  ngOnInit() {
    this.getSelectedExtra();
  }
  @Input() extra1: number = -1;

  formChanged(carConfigurationFormChanged : any) {
    const index = Math.trunc(this.extra1);//important, otherwise the Map.get returns undefined
    const record : Extra | undefined = this.extraById.get(index);
    this.gesamtpreis = "" + record?.preis?.toString() + " " + Math.random().toString();//909 0.784784
  }
}

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

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