[英]Angular2 'this' is undefined
我有一个代码如下:
export class CRListComponent extends ListComponent<CR> implements OnInit {
constructor(
private router: Router,
private crService: CRService) {
super();
}
ngOnInit():any {
this.getCount(new Object(), this.crService.getCount);
}
ListComponent代码是这样的
@Component({})
export abstract class ListComponent<T extends Listable> {
protected getCount(event: any, countFunction: Function){
let filters = this.parseFilters(event.filters);
countFunction(filters)
.subscribe(
count => {
this.totalItems = count;
},
error => console.log(error)
);
}
CRService的相应服务代码片段是这样的:
getCount(filters) {
var queryParams = JSON.stringify(
{
c : 'true',
q : filters
}
);
return this.createQuery(queryParams)
.map(res => res.json())
.catch(this.handleError);
}
现在当我的ngOnInit()
运行时,我收到一个错误:
angular2.dev.js:23925 EXCEPTION:TypeError:无法读取[null]中未定义的属性'createQuery'
原始异常:TypeError:无法读取未定义的属性“createQuery”
所以基本上, this
在return this.createQuery(queryParams)
声明将是无效的。 有人知道这有可能吗?
问题出在这里:
gOnInit():any {
this.getCount(new Object(), this.crService.getCount); // <----
}
由于您引用了对象外部的函数。 您可以在其上使用bind
方法:
this.getCount(new Object(), this.crService.getCount.bind(this.crService));
或将其包装成箭头功能:
this.getCount(new Object(), (filters) => {
return this.crService.getCount(filters));
});
第二种方法是首选方法,因为它允许保留类型。 有关详细信息,请参阅此页面:
为了解决这个错误,我把所有内脏从我的函数中拉出来导致错误并将其扔到另一个函数中,然后错误就消失了。
例:
我有这个功能,里面有一些代码
this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
// bunch of code to evaluate click event
// this is the code that had the "this" undefined error
});
我把代码拉出来并把它放在一个外部的公共函数中,这里是完成的代码:
this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
this.evaluateClick(event);
});
evaluateClick(evt: MouseEvent){
// all the code I yanked out from above
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.