问题是传递给视图子项的属性变为undefined
:
父组件:
@Component({
selector: 'app-searchbox',
template: `
<app-artifact-list [artifacts]="searchResults"></app-artifact-list>
`
})
export class SearchboxComponent implements OnInit {
// explicitly initialize the property
// the same effect with constructor initialization
searchResults: Artifact[] = [new Artifact()];
constructor(private artifactService: ArtifactService) {
}
ngOnInit(): void {
this.pollService(this.artifactService.findByQuery('guice'));
}
private pollService(request: Observable<Artifact[]>) {
return request.subscribe(this.fillInResults);
}
private fillInResults(result: Artifact[]) {
result.forEach(console.log);
for (let obj of result) {
// this.searchResults is undefined! why?
this.searchResults.push(obj);
}
}
}
子组件:
@Component({
selector: 'app-artifact-list',
template: `
<h1>{{_artifacts | json}}</h1>
`
})
export class ArtifactListComponent implements OnChanges {
private _artifacts: Artifact[] = [];
ngOnChanges(changes: SimpleChanges): void {
console.log('Property changed');
}
@Input()
set artifacts(artifacts: Artifact[]) {
console.error('Property changed');
this._artifacts = artifacts;
}
}
在构造函数调用期间,我看到该属性已正确初始化,但在回调方法中它变为undefined
。
它与this
有什么关联吗?也许this.searchResults
引用了回调中的其他内容?
答案 0 :(得分:0)
在this
对“函数引用”范围内使用它进行一些调查后,我发现实际上this
引用了另一个对象。我喜欢javascript:)
所以解决方法是:
private pollService(request: Observable<Artifact[]>) {
return request.subscribe(
this.fillInResults.bind(this)
);
}
private fillInResults(result: any) {
result.forEach(console.log);
for (let obj of result) {
this.searchResults.push(obj);
}
}
或使用胖箭头功能:
private pollService(request: Observable<Artifact[]>) {
return request.subscribe(
result => this.fillInResults(result)
);
}
private fillInResults(result: any) {
result.forEach(console.log);
for (let obj of result) {
this.searchResults.push(obj);
}
}
有关详细说明,请参阅此问题:Angular2 component's “this” is undefined when executing callback function