TypeError:无法读取Angular 2 Promises上未定义的属性'then'

时间:2016-10-19 08:31:15

标签: angular

我在使用根段路由的组件上有以下代码。

ngOnInit() {
    ...

    this.route.queryParams.forEach((params: Params) => {
        if (params['scrollTo']) {
            this.checkIfDataLoaded().then(() => { 
                this.scrollToSection(params['scrollTo']);
            })
        }
    });
}

checkIfDataLoaded() {
    if (this.firstLoaded && this.secondLoaded && this.thirdnLoaded) {
        return new Promise((resolve, reject) => {
            resolve(true);
        });
    }
}

它工作正常,直到我切换到路由并返回到我的根段,我注意到调试器我得到了这个错误

TypeError: Cannot read property 'then' of undefined
    at eval (http://localhost:54396/app/my.component.js:58:42)
    at SafeSubscriber.eval [as _next] (http://localhost:54396/node_modules/rxjs/Observable.js:108:21)
    at SafeSubscriber.__tryOrSetError (http://localhost:54396/node_modules/rxjs/Subscriber.js:232:16)
    at SafeSubscriber.next (http://localhost:54396/node_modules/rxjs/Subscriber.js:174:27)
    at Subscriber._next (http://localhost:54396/node_modules/rxjs/Subscriber.js:125:26)
    at Subscriber.next (http://localhost:54396/node_modules/rxjs/Subscriber.js:89:18)
    at BehaviorSubject._subscribe (http://localhost:54396/node_modules/rxjs/BehaviorSubject.js:28:24)
    at BehaviorSubject.Observable.subscribe (http://localhost:54396/node_modules/rxjs/Observable.js:56:27)
    at eval (http://localhost:54396/node_modules/rxjs/Observable.js:87:38)
    at new ZoneAwarePromise (http://localhost:54396/node_modules/zone.js/dist/zone.js:467:29)

知道发生了什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

checkIfDataLoaded没有返回Promise时会发生以下错误:

checkIfDataLoaded() {
    if (this.firstLoaded && this.secondLoaded && this.thirdnLoaded) {
        return new Promise((resolve, reject) => {
            resolve(true);
        });
    }
    /// <<<=== here nothing is returned
}