TypeError: Cannot read property 'Id' of undefined on edit view template - Angular 2

TypeError: Cannot read property 'Id' of undefined on edit view template - Angular 2

好吧,我一直在面对可怕的事情:

TypeError: Cannot read property 'Id' of undefined

开始之前:

@angular/cli: 1.4.4 节点:6.10.3 npm:3.10.10

只是为了提供更多上下文,我正在尝试执行一种数据绑定方式来编辑组件,方法是从其组件 class 中获取 Id 并单向流动以显示视图模板。就这些了。

以下内容有望重现问题并找出解决方案。

  1. SQL Table 定义:
CREATE TABLE [ExampleTable]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Col2] [nvarchar](50) NULL,
    [Col3] [int] NULL,
    [Col4] [int] NULL
)
  1. ExampleTable.ts

export interface ExampleTable {
    Id;
    Col2;
    Col3;
    Col4;
}

export class CreateExampleTableModel {
    SomeForeignKey?: number;
    Col2: string;
    Col2: number; 
    Col2: number; 
}

export class EditExampleTable {

}

  1. 空-tables.component.ts

import {
  Component
} from '@angular/core';
import {
  Router
} from "@angular/router";
import {
  EmptyTableServiceService
} from "../../services/empty-table.service";
import {
  EmptyTable
} from "../../models/outModels/EmptyTable";


@Component({
  selector: 'app-empty-tables',
  templateUrl: './empty-tables.component.html',
  styleUrls: ['./empty-tables.component.css']
})
export class EmptyTablesComponent {
  //Table data
  emptyTable: EmptyTable[];


  constructor(
    private router: Router,
    private emptyTableServiceService: EmptyTableServiceService) {

  }

  edit(emptyTable: EmptyTable) {
    this.router.navigate(['emptyTables/edit', emptyTable.Id]);
  }
}

  1. 空Table服务:

import {
  Injectable
} from '@angular/core';
import {
  Http
} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {
  EmptyTable,
  CreateExampleTableModel
} from "../models/outModels/EmptyTable";

@Injectable()
export class EmptyTableService {
  constructor(private http: Http, ) {}

getEmptyTable(Id: string): Promise<EmptyTable> {
    return this.http.get(`${this.auth.apiUrl}/api/emptyTables/get/${Id}`, { headers: this.auth.header })
        .toPromise()
        .then(response => response.json() as EmptyTable)
        .catch(error => this.logging.handleError(error));
}

  update(emptyTable: EmptyTable): Promise < EmptyTable > {
    return this.http.post(`${this.auth.apiUrl}/api/emptyTables/update`, JSON.stringify(emptyTable), {
        headers: this.auth.header
      })
      .toPromise()
      .then(response => response.json() as EmptyTable)
      .catch(error => this.logging.handleError(error));
  }
}

  1. 空Table编辑组件:

import {
  Component,
  OnInit
} from '@angular/core';
import {
  ActivatedRoute,
  ParamMap,
  Router
} from '@angular/router';
import {
  EmptyTableService
} from "../../../services/empty-table.service";
import {
  EmptyTable
} from "../../../models/outModels/EmptyTable";

export class EmptyTableEditComponent implements OnInit {

  model: EmptyTable;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private emptyTableService: EmptyTableService
  ) {}

  ngOnInit() {
    this.loading = true;
    this.route.paramMap
      .switchMap((params: ParamMap) => this.emptyTableService.getEmptyTable(params.get('Id')))
      .subscribe(emptyTable => {
        this.model = emptyTable;
      });
  }

  goBack(): void {
    this.router.navigate(['/emptyTables']);
  }

  save(): void {
    this.loading = true;
    this.emptyTableService.update(this.model).then(
      emptyTable => {
        this.model = emptyTable;
      },
      error => {
        console.log(error);
      }
    );
  }
}

我怀疑在我的 getEmptyTable(Id: string) 中 returns EmptyTablesPromise 是我将我的 Id 参数作为字符串值传递,而在我的table 从我的数据库中定义它是一个 integer 但是根据我的理解,url 参数始终为字符串格式。我尝试了以下方法:

我。将我的 Id 设置为 number 数据类型,然后我在 apiUrl 中的 Id 参数上调用 toString(),如下所示:

 getEmptyTable(Id: number): Promise<EmptyTable> {
        return this.http.get(`${this.auth.apiUrl}/api/emptyTables/get/${Id.toString()}`, { headers: this.auth.header })
            .toPromise()
            .then(response => response.json() as EmptyTable)
            .catch(error => this.logging.handleError(error));
    }

但这并没有太大的区别。最后,请找到我渲染的视图模板:

<div class="container">
  <p-messages [(value)]="messages"></p-messages>
  <p-panel *ngIf="model">
    <p-header>
      Edit EmptyTable {{model.Name}}
    </p-header>
    <form name="form" (ngSubmit)="save()">

      <div class="form-group">
        <label>Col 2</label>
        <input type="text" class="form-control" name="col2" [(ngModel)]="model.Col2" required />
      </div>

      <div class="form-group">
        <label>Col 3</label>
        <input type="text" class="form-control" name="col3" [(ngModel)]="model.Col3" required />
      </div>

      <div class="form-group">
        <button pButton type="button" class="ui-button-secondary" (click)="goBack()" label="Back" icon="fa-chevron-left"></button>
        <button pButton class="ui-button-success pull-right" label="Save" icon="fa-save"></button>
        <app-loader *ngIf="loading"></app-loader>
      </div>
    </form>
  </p-panel>
</div>

总结一下,它在以下函数中抱怨:

  edit(emptyTable: EmptyTable) {
        this.router.navigate(['emptyTables/edit', emptyTable.Id]);
    }

注意:请不要运行这些片段,因为它们没有输出。这是格式化我的代码的最快方法。手动缩进是不削减它。

发现问题如下:

 <ng-template let-user="rowData" pTemplate="body">
                    <button type="button" pButton (click)="edit(distributor)" icon="fa-edit"></button>
                </ng-template>

let-user 应该更改为 let-distributor 并且一切正常。