Ошибка Angular6 - Невозможно прочитать свойство mapName из undefined

Я реализую проект wep, используя Mean Stack с Angular 6. Здесь я должен отправить форму с загруженным файлом. Ниже мой html.

<ng-template #content let-c = "close" let-d = "dismiss">
  <div class = "modal-header">
    <h4 class = "modal-title" id = "modal-basic-title">New Map</h4>
  </div>
  <div class = "modal-body">
    <form #mapsForm = "ngForm" enctype = "multipart/form-data">
      <div class = "form-group">
        <label for = "name">Name</label>
        <div class = "input-group">
          <input type = "text" id = "mapNameId" class = "form-control form-control-sm  " name = "mapName" [(ngModel)] = "currentMapDetails.mapName" name = "firstName" >
        </div>
        <br>
        <label for = "geoRefMap">Geo- reference Map</label>
        <div class = "input-group">
          <input type = "file" class = "form-control" #fileInput name = "milespecMap" ng2FileSelect [uploader] = "uploader" (change) = "handleFileInput($event.target.files)"
          />
        </div>
        <br>
        <div>
          <button type = "submit" (click) = "updateInfo()" class = "btn btn-sm btn-rectangle btn-default text-case" id = "updatebtn">Update</button>
        </div>
        <br>
        <label for = "shapeFile">Shape Files</label>
        <div class = "boxed">
          <div class = "input-group">
            <input id = "shapeFile" class = "form-control" name = "shapeFile">
            <img src = "../../../../../assets/images/maps/Browse.png" width = "40" height = "40" style = " position: absolute; top: 1px; right: 1px"
              (click) = "search(); " />
          </div>
        </div>
      </div>
    </form>


  </div>
  <div class = "modal-footer">
    <nb-card class = "action-buttons">
      <div class = "form-input-group">
        <div class = "row">
          <div class = "">
            <button type='button' (click) = "modal.close('Save click')" class = "btn btn-sm btn-rectangle btn-default text-case">Save
            </button>
          </div>
          <div class = "">
            <button type='button' (click) = "modal.cancel('cancel click')" class = "btn btn-sm btn-rectangle btn-default text-case">Cancel</button>
          </div>

        </div>
      </div>
    </nb-card>
  </div>
  <br>

</ng-template>

<hr>
<pre>{{closeResult}}</pre>
<nb-card>
  <nb-card-header>
  </nb-card-header>
  <nb-card-body>
    <div>
      <div class = "col-lg-3" style = "float: left; ">
        <div class = "verticalLine">
        </div>
      </div>

      <nb-card class = "action-buttons">
        <div class = "form-input-group">
          <div class = "row">
            <div class = "">
              <button type='button' (click) = "openModal(content)" class = "btn btn-sm btn-rectangle btn-default text-case">Add
              </button>
            </div>
            <div class = "">
              <button type='button' (click) = "editMap()" class = "btn btn-sm btn-rectangle btn-default text-case">Edit</button>
            </div>
            <div class = "">
              <button type='button' (click) = "deleteMap()" class = "btn btn-sm btn-rectangle btn-default text-case">Delete</button>
            </div>
          </div>
        </div>
      </nb-card>

    </div>
  </nb-card-body>
</nb-card>

Там у меня есть кнопка «Добавить» в map.component.html, и щелчок по этой кнопке открывает модальное окно. Следующее - мой ts.

import { Component, OnInit } from '@angular/core';
import { NgbModal, ModalDismissReasons } from '../../../../../../node_modules/@ng-bootstrap/ng-bootstrap';
import { HttpResponse, HttpEventType } from '@angular/common/http';
import { Http } from '../../../../../../node_modules/@angular/http';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
import { Map } from './models/map';
import { Router } from '@angular/router';
import { MapsService } from '../../services/maps.service';

const URL = '/mapInfo/uploadMap';
@Component({
  selector: 'maps',
  templateUrl: './maps.component.html',
  styleUrls: ['./maps.component.scss']
})
export class MapsComponent implements OnInit {
  closeResult: string;
  currentMapDetails: Map;
  selectedFile: File = null;

  public uploader: FileUploader = new FileUploader({ url: URL, itemAlias: 'milespecMap', });
  constructor(private modalService: NgbModal,
    private mapsService: MapsService,
    private http: Http,
    private router: Router
  ) { }

  ngOnInit() {
  }
  openModal(content: any) {
    this.modalService.open(content).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }

  handleFileInput(file: FileList) {
    this.selectedFile = file.item(0);
    var reader = new FileReader();

    reader.onload = (event: any) => {
      this.currentMapDetails.milespecUrl = event.target.result;

    }
    reader.readAsDataURL(this.selectedFile);
  }

  updateInfo() {
    this.uploader.uploadAll(); ///image upload
    this.update();
  }

  update() {

    this.mapsService.updateMap(this.currentMapDetails).subscribe(res => {
      this.currentMapDetails;
    }, (err) => {
      console.info(err);
    });
    console.info(this.currentMapDetails);
  }
}

Ниже приведен мой класс карты.

export class Map {
  _id: string;
  mapName: string;
  milespecUrl: string;
}

Но когда я привязываю поле имени карты к 'currentMapDetails' (например: [(ngModel)] = "currentMapDetails.mapName"). Он не открывает мое модальное окно и дает следующую ошибку. Невозможно прочитать свойство mapName из undefined

currentMapDetails: Map = {} ;
Fateme Fazli 31.10.2018 13:10
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Angular и React для вашего проекта веб-разработки?
Angular и React для вашего проекта веб-разработки?
Когда дело доходит до веб-разработки, выбор правильного front-end фреймворка имеет решающее значение. Angular и React - два самых популярных...
Эпизод 23/17: Twitter Space о будущем Angular, Tiny Conf
Эпизод 23/17: Twitter Space о будущем Angular, Tiny Conf
Мы провели Twitter Space, обсудив несколько проблем, связанных с последними дополнениями в Angular. Также прошла Angular Tiny Conf с 25 докладами.
Угловой продивер
Угловой продивер
Оригинал этой статьи на турецком языке. ChatGPT используется только для перевода на английский язык.
Мое недавнее углубление в Angular
Мое недавнее углубление в Angular
Недавно я провел некоторое время, изучая фреймворк Angular, и я хотел поделиться своим опытом со всеми вами. Как человек, который любит глубоко...
Освоение Observables и Subjects в Rxjs:
Освоение Observables и Subjects в Rxjs:
Давайте начнем с основ и постепенно перейдем к более продвинутым концепциям в RxJS в Angular
1
1
194
3
Перейти к ответу Данный вопрос помечен как решенный

Ответы 3

You are encountered with this undefined error since currentMapDetails is not initialized when the Component was rendered. What you can do is just put one if condition before you use it. It will display the mapName once the currentMapDetails is retrieved and available.

<div class = "input-group" *ngIf = "currentMapDetails" >
    <input type = "text" id = "mapNameId" class = "form-control form-control-sm "
       name = "mapName" [(ngModel)] = "currentMapDetails.mapName" name = "firstName" >
</div>
Ответ принят как подходящий

Вам просто нужно инициализировать свойство currentMap Details

currentMapDetails: Map = new Map();

когда вы объявляете currentMapDetails, вы только что установили его тип, но все еще имеете значение undefined

you have to change the class name Map to something else it 's will have conflect with javascript Map

Вы только что объявили currentMapDetails как Map. Это еще не инициализирован. Следовательно, возникает ошибка. Поскольку сам currentMapDetails не определен. Таким образом, вы не можете получить доступ к его собственности mapName.

Вы можете решить эту проблему, добавив метку ? в html-представление: (Примечание: это просто позволит избежать ошибки).

[(ngModel)] = "currentMapDetails?.mapName"

ИЛИ

Вы должны инициализировать его в ngOnInit(),

ngOnInit() { 
    currentMapDetails: Map = new Map();
}

Надеюсь это поможет.,

Другие вопросы по теме