模板错误:无法设置只有getter的[object Object]的属性堆栈

时间:2017-01-18 19:22:35

标签: angular

我有一个组件,如下所示,我检索一个Course对象:

import {Component, OnInit} from "@angular/core";
import {CourseService} from "../shared/course.service";
import {Course} from "../shared/Course";

@Component({
  selector: 'app-course-list',
  templateUrl: './course-list.component.html',
  styleUrls: ['./course-list.component.css']
})

export class CourseListComponent implements OnInit {

  course : Course;
  name : string;

  constructor(private courseService: CourseService) {

  }

  ngOnInit() {
    this.courseService.getCourse(1).subscribe(response => {
      this.course = response;
      this.name = this.course.name;
      console.log(this.course);
    });
  }
}

检索看起来有效。为什么我在尝试时会在模板中出现错误:

<p>
  Editing Course : {{course.name}} < -error
  Editing Course : {{name}} <-- works
</p>

错误:

error_handler.js:50EXCEPTION: Error in ./CourseListComponent class CourseListComponent - inline template:0:3 caused by: Cannot read property 'name' of undefined
ErrorHandler.handleError @ error_handler.js:50
(anonymous) @ application_ref.js:259
ZoneDelegate.invoke @ zone.js:242
onInvoke @ ng_zone.js:269
ZoneDelegate.invoke @ zone.js:241
Zone.run @ zone.js:113
(anonymous) @ zone.js:535
ZoneDelegate.invokeTask @ zone.js:275
onInvokeTask @ ng_zone.js:260
ZoneDelegate.invokeTask @ zone.js:274
Zone.runTask @ zone.js:151
drainMicroTaskQueue @ zone.js:433
error_handler.js:52ORIGINAL EXCEPTION: Cannot read property 'name' of undefined
ErrorHandler.handleError @ error_handler.js:52
(anonymous) @ application_ref.js:259
ZoneDelegate.invoke @ zone.js:242
onInvoke @ ng_zone.js:269
ZoneDelegate.invoke @ zone.js:241
Zone.run @ zone.js:113
(anonymous) @ zone.js:535
ZoneDelegate.invokeTask @ zone.js:275
onInvokeTask @ ng_zone.js:260
ZoneDelegate.invokeTask @ zone.js:274
Zone.runTask @ zone.js:151
drainMicroTaskQueue @ zone.js:433
error_handler.js:55ORIGINAL STACKTRACE:
ErrorHandler.handleError @ error_handler.js:55
(anonymous) @ application_ref.js:259
ZoneDelegate.invoke @ zone.js:242
onInvoke @ ng_zone.js:269
ZoneDelegate.invoke @ zone.js:241
Zone.run @ zone.js:113
(anonymous) @ zone.js:535
ZoneDelegate.invokeTask @ zone.js:275
onInvokeTask @ ng_zone.js:260
ZoneDelegate.invokeTask @ zone.js:274
Zone.runTask @ zone.js:151
drainMicroTaskQueue @ zone.js:433
error_handler.js:56TypeError: Cannot read property 'name' of undefined
    at CompiledTemplate.proxyViewClass.View_CourseListComponent0.detectChangesInternal (/AppModule/CourseListComponent/component.ngfactory.js:34:87)

2 个答案:

答案 0 :(得分:2)

您正在异步获取数据。与course变量undefined第一次一样,您可以使用安全导航操作符(?。)来防止此错误

{{course?.name}} 

另见

答案 1 :(得分:0)

就我而言,我在单元测试运行中遇到此错误。问题是测试用例中缺少一个指令。