Как решить Angular TypeError: Невозможно прочитать свойство 'name' из неопределенного - PullRequest
0 голосов
/ 12 октября 2019

После обновления моего приложения с углового 4 на угловое 8 появляется ошибка, которую я не могу устранить. Ошибка выглядит следующим образом:

OrderOverviewComponent.html:46 ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateRenderer] (OrderOverviewComponent.html:46)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:45293)
at checkAndUpdateView (core.js:44276)
at callViewAction (core.js:44636)
at execEmbeddedViewsAction (core.js:44593)
at checkAndUpdateView (core.js:44271)
at callViewAction (core.js:44636)
at execEmbeddedViewsAction (core.js:44593)
at checkAndUpdateView (core.js:44271)
at callViewAction (core.js:44636)

Мой файл TypeScript выглядит так:

import {DatabaseService} from '../../services/database.service';
import {UtiliesService} from '../../services/utilies.service';
import {AdditionalInformationInsertionComponent} from '../utils/additional-information-insertion/additional-information-insertion.component';
import {PrinterService} from '../../services/printer.service';
import {Component, OnInit, ViewChild} from '@angular/core';
import {Router} from '@angular/router';
import {ModalFeedbackEditComponent} from '../utils/modal-feedback-edit/modal-feedback-edit.component';
@Component({
  selector: 'app-order-overview',
  templateUrl: './order-overview.component.html',
  styleUrls: ['./order-overview.component.scss']
})
export class OrderOverviewComponent implements OnInit {

  orders: any = [];
  machines: any = [];
  selectedMachine: any = [];
  activeOrderId = -1;

  @ViewChild(AdditionalInformationInsertionComponent, {static: false}) child: AdditionalInformationInsertionComponent;


  constructor(private router: Router, private databaseService: DatabaseService, private utilityService: UtiliesService, private printerService: PrinterService) {
  }


  ngOnInit() {
    this.selectedMachine = this.utilityService.getItem('selectedMachine');

    this.databaseService.getAllMachines().subscribe((x) => {
      this.machines = x;
      this.machines = this.machines.sort(function(a, b) {return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0); } );
      this.machines.splice(0, 0, {machineId: -1, name: '-------------'});
    });

    if (this.selectedMachine !== null) {
      this.databaseService.getOrdersForMachineId(this.selectedMachine.machineId).subscribe((x) => {
        this.orders = x;
        this.activeOrderId = this.utilityService.getActiveOrder()['orderingId'];
        console.log('TTT', this.activeOrderId);
      });
      return;
    } else {
      this.selectedMachine = [];
    }

    this.databaseService.getAllOrders().then((x) => {
      this.orders = x;
      this.activeOrderId = this.utilityService.getActiveOrder()['orderingId'];
    });
  }

  public startOrder(order: any)  {
    this.utilityService.setActiveOrder(order);
    this.activeOrderId = order['orderingId'];
    console.log('ORDER TOOL VERSION', order);
    if (order.tool.version == null) {
      this.child.openAdditionalDialog();
    } else {
      // this.printerService.setPrintLabel(order.machine.printerAddress, order.printDescription);
      this.router.navigateByUrl('/orderdata');
    }


  }
  public showOrderData(orderId) {
    this.router.navigateByUrl('/orderdata/' + orderId);
  }

  public changeMachine(machine: any) {
    this.orders =  [];
    this.selectedMachine = machine;
    this.utilityService.storeItem('selectedMachine', machine);
    if (this.selectedMachine.machineId < 0) {
      this.databaseService.getAllOrders().then((x) => {
        this.orders = x;
      });
      return;
    }
    this.databaseService.getOrdersForMachineId(this.selectedMachine.machineId).subscribe((x) => {
      this.orders = x;
    });
  }

  compareMachines(c1: any, c2: any): boolean {
    return c1 && c2 ? c1.machineId === c2.machineId : c1 === c2;
  }

}

И мой HTML-файл выглядит так:

<app-additional-information-insertion></app-additional-information-insertion> <!-- Nur anzeigen, wenn noch keine Variante drinsteht-->
<div class="row">
  <div class="col-12">
    <div class="card">
      <h4 class="card-header">Auftragsübersicht
        <div class="form-inline pull-right" style="display: inline;" >
          <label style="display: inline; font-size: 1rem;" for="machine">Machine: </label>
          <select [compareWith]="compareMachines"  class="form-control form-control-sm" id="machine" required style="margin: -10px 5px -7px;" [ngModel]="selectedMachine" (ngModelChange)="changeMachine($event)">
          <option *ngFor="let machine of machines" [ngValue]="machine" [selected]="machine.machineId == selectedMachine.machineId">{{machine.name}}</option>
        </select>
        </div>
      </h4>
      <div class="card-body">
        <table class="table table-sm">
          <thead>
          <tr>
            <th scope="col">Auftrag</th>
            <th scope="col">Artikel</th>
            <th scope="col">Bezeichnung</th>
            <th scope="col">Menge</th>
            <th scope="col">Behälter</th>
            <th scope="col">Anlage</th>
            <th scope="col" ></th>
          </tr>
          </thead>
          <tbody>
          <tr *ngFor="let order of orders" >
            <th *ngIf="order['orderFinished'] !== 1" (click)="showOrderData(order['orderingId'])" scope="row">{{order['orderingId']}}</th>
            <td *ngIf="order['orderFinished'] !== 1" (click)="showOrderData(order['orderingId'])" >{{order['article']['name']}}</td>
            <td *ngIf="order['orderFinished'] !== 1" (click)="showOrderData(order['orderingId'])" >{{order['article']['description']}}</td>
            <td *ngIf="order['orderFinished'] !== 1" (click)="showOrderData(order['orderingId'])" >{{order['totalQuantity']}}</td>
            <td *ngIf="order['orderFinished'] !== 1" (click)="showOrderData(order['orderingId'])" >{{order['quantityOfContainer']}} {{order['typeOfContainer']}}</td>
            <td *ngIf="order['orderFinished'] !== 1" (click)="showOrderData(order['orderingId'])" >{{order['machine']['name']}}</td>
            <td *ngIf="order['orderFinished'] !== 1">
              <button class="btn btn-block  btn-sm btn-outline-primary" *ngIf="order['orderingId'] != activeOrderId " (click)="startOrder(order)">Auftrag starten</button>
              <button class="btn btn-block  btn-sm btn-primary" *ngIf="order['orderingId'] === activeOrderId" (click)="startOrder(order)">Auftrag gestartet</button>
              <!--<span *ngIf="order['orderActive'] === 1">Läuft</span>-->
            </td>

          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

I 'Я благодарен за любые предположения или помощь, потому что, честно говоря, у меня нет идей попробовать что-либо еще! Спасибо!

1 Ответ

0 голосов
/ 12 октября 2019

Не могли бы вы проверить, если getAllMachines () приводит к записи в консоли Observable Try в журнале подписки и посмотреть, назначен ли массив машин определенному объекту со значением

 this.databaseService.getAllMachines().subscribe((x) => {
   console.log(x);
          this.machines = x;
          this.machines = this.machines.sort(function(a, b) {return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0); } );
          this.machines.splice(0, 0, {machineId: -1, name: '-------------'});
        });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...