我有一个代码如下:
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: Cannot read property
‘createQuery’ of undefined in [null]ORIGINAL EXCEPTION:
TypeError: Cannot read property ‘createQuery’ of undefined
所以基本上,返回this.createQuery(queryParams)语句中的this将为null.有人知道这有可能吗?
解决方法
问题出在这里:
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)); });
第二种方法是首选方法,因为它允许保留类型.有关详细信息,请参阅此页面:
> https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html