ChangeDetectorRef detectChanges()之后的组件的null属性

时间:2017-07-06 00:25:41

标签: angular

为什么在调用changeDetector后组件为空?

@HostListener('window:resize', ['$event'])
onResize(event) {
    clearTimeout(this.resizeTimer);
    this.resizeTimer = setTimeout(this.resizeObj(), 500);
}

resizeObj() {
    this.applyUpd(this.dataList);
    this.changeDetector.detectChanges();
}



applyUpd(dataList: Data[]) {

    for (var i = 0; i < this.dataList.length; i++) {
        this.dataList[i].applyData(this.width, this.height);
    }        

}

构造

constructor(private changeDetector: ChangeDetectorRef) {        
        this.resizeTimer;
        this.route.data
            .subscribe(( data: { dataList: Data[] }) => {
                // ...
            });
    }

错误:

core.es5.js:1084 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'dataList' of null
TypeError: Cannot read property 'dataList' of null
    at Object.eval [as updateDirectives] (DataListComponent.html:7)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12806)
    at checkAndUpdateView (core.es5.js:12144)
    at callWithDebugContext (core.es5.js:13206)
    at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.es5.js:12746)
    at ViewRef_.detectChanges (core.es5.js:10218)
at DataListComponent.webpackJsonp.151.DataListViewComponent.applyUpd(data-list-view.component.ts:73)
    at SafeSubscriber._next (data-list.component.ts:55)
    at SafeSubscriber.__tryOrSetError (Subscriber.js:247)
    at SafeSubscriber.next (Subscriber.js:187)
    at Object.eval [as updateDirectives] (DataListComponent.html:7)

1 个答案:

答案 0 :(得分:1)

错误在onResize(event)方法中。 在组件init之前调用this.changeDetector.detectChanges()。

变化

this.resizeTimer = setTimeout(this.resizeObj(), 500);

this.resizeTimer = setTimeout(this.resizeObj, 500);