Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

TypeError: Cannot read property 'then' of undefined on Angular 2 Promises

I have the following code, on a component that uses the root segment route.

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);
        });
    }
}

It works fine until i switch trough routes and get back to my root segment, I noticed with the debugger that I get this error

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)

Any idea what is happening and how to solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When checkIfDataLoaded doesn't return a Promise this error occurs:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...