Angular2'this'未定义

Sle*_*er9 7 javascript angular2-services angular

我有一个代码如下:

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);
    }
Run Code Online (Sandbox Code Playgroud)

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)
            );
    }
Run Code Online (Sandbox Code Playgroud)

CRService的相应服务代码片段是这样的:

getCount(filters) {
    var queryParams = JSON.stringify(
        {
            c : 'true',
            q : filters
        }
    );

    return this.createQuery(queryParams)
        .map(res => res.json())
        .catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)

现在,当我ngOnInit()跑步时,我收到一个错误:

angular2.dev.js:23925 EXCEPTION:TypeError:无法读取[null]中未定义的属性'createQuery'

原始异常:TypeError:无法读取未定义的属性"createQuery"

所以基本上,thisreturn this.createQuery(queryParams)声明将为空.有人知道这有可能吗?

Thi*_*ier 10

问题出在这里:

gOnInit():any {
    this.getCount(new Object(), this.crService.getCount); // <----
}
Run Code Online (Sandbox Code Playgroud)

由于您引用了对象外部的函数.你可以使用bind它的方法:

this.getCount(new Object(), this.crService.getCount.bind(this.crService));
Run Code Online (Sandbox Code Playgroud)

或将其包装成箭头功能:

this.getCount(new Object(), (filters) => {
  return this.crService.getCount(filters));
});
Run Code Online (Sandbox Code Playgroud)

第二种方法是首选方法,因为它允许保留类型.有关详细信息,请参阅此页面: