我有一个简单的组件类,如下所示:
import { Component } from '@angular/core';
import { ControlService } from '../services/control-service';
@Component({
templateUrl: './control-bar.component.html',
styleUrls: ['./control-bar.component.less']
})
export class ControlBarComponent {
get context(): any { return this.controls.context; }
constructor(private controls: ControlService) { }
is(contextName) {
return this.context.constructor.name == contextName;
}
}
当我尝试为给定代码编写单元测试时,就会出现问题。我收到以下错误:
TypeError:无法读取未定义的属性“ constructor” 在ControlBarComponent ../ src / app / courses / control -bar.component.ts.ControlBarComponent.is(http://localhost:9876/ _karma_webpack_ / webpack:/src/app/courses/control-bar.component.ts:12:33) 在Object.eval [作为updateDirectives] (ng:///DynamicTestModule/ControlBarComponent.ngfactory.js:111:25)
在玩过tod并尝试找到答案之后,我尝试了以下不再引发错误的代码。
// Same except for the following line
context = () => this.controls.context;
// replaces
get context(): any { return this.controls.context; }
那么该解决方案有什么缺点吗?如果是这样,什么时候应该使用这两个代码构造?