ERROR TypeError: Cannot read property 'id' of undefined angular at DepartmentListComponent_li_3_Template (department-list.component.ts:12)

ERROR TypeError: Cannot read property 'id' of undefined angular at DepartmentListComponent_li_3_Template (department-list.component.ts:12)

我最近开始学习 angular 并遵循本教程 https://www.youtube.com/watch?v=qh5nHv-4aw0&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=25 关于 Angular

中的路由参数

我被这个错误困住了,当然用谷歌搜索了它,但没有得到解决方案。

文件如下:

部门-list.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-department-list',
  template: `
    <h3>
      department-list works!
    </h3>
    
    <ul>
      <li *ngFor="let deparment of departments">
        <span>{{department.id}}</span>{{department.name}}
      </li>
    </ul>
  `,
  styles: [
  ]
})

export class DepartmentListComponent implements OnInit {

  constructor() { }

  departments = [
    {"id":1,"name":"Angular"},
    {"id":2,"name":"Node"},
    {"id":3,"name":"MongoDB"},
    {"id":4,"name":"Ruby"},
    {"id":5,"name":"Bootstrap"}    
  ]

  ngOnInit() {
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    routingComponents,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DepartmentListComponent } from './department-list/department-list.component';
import {EmployeeListComponent} from './employee-list/employee-list.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const routes: Routes = [
  { path: '', redirectTo: '/departments', pathMatch: 'full'},
  { path: 'departments', component:DepartmentListComponent},
  { path: 'employees', component:EmployeeListComponent},
  { path: "**", component:PageNotFoundComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }
export const routingComponents = [DepartmentListComponent, 
                                  EmployeeListComponent,
                                   PageNotFoundComponent];

这只是一个小错别字。

<li *ngFor="let deparment of departments">
        <span>{{department.id}}</span>{{department.name}}
      </li>

您的迭代对象是 deparment(没有 t),而您访问 department(有 t)。只需将 t 添加到您的迭代对象