Angular 2 - 在执行服务之前等待布尔值为真

Angular 2 - Waiting for boolean to be true before executing service

我有一个使用 ng2-page-scroll 模块的导航菜单。

我使用井号标签链接浏览页面。

问题是如果我跨路线工作,数据需要一些时间来加载,所以服务通常滚动到我的部分,然后加载整个数据,并且感兴趣的部分将不再在屏幕上折叠,因此用户需要手动滚动才能到达感兴趣的部分。这使得整个菜单变得毫无用处。

所以我在所有部分都使用 EventEmitter,在 "scrollable" 页面中设置布尔值,一切都很好...

但我不知道如何等待 allDataLoaded 布尔值变为真。

我尝试使用 promises

这是我的代码到目前为止的样子。

导航菜单组件

HTML

<a [routerLink]="['']" [queryParams]="{ scrollTo: '#home' }">
<a [routerLink]="['']" [queryParams]="{ scrollTo: '#contact' }">
<a [routerLink]="['']" [queryParams]="{ scrollTo: '#about' }">

HTML of component using root segment

<componentOne (dataLoadedEvent)="homeLoaded = true; checkIfDataLoaded()"></componentOne>

使用根段的组件的 TS

homeLoaded: boolean = false;
contactLoaded: boolean = false;
aboutLoaded: boolean = false;

allDataLoaded: boolean = false;

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

checkIfDataLoaded() {
    if (this.homeLoaded && this.contactLoaded && this.aboutLoaded) {
        //this.allDataLoaded = true;
        return new Promise((resolve, reject) => {
            resolve(true);
        });
    }
}

正如 Günter Zöchbauer 在这里回答 ( ) 的另一个问题,代码将中断 TypeError: Cannot read property 'then' of undefined

TL;DR 在等待布尔值变为 true/false 时使用 promise 的正确方法是什么?

问题出在您的代码中,特别是在 checkIfDataLoaded() 方法中,而不是因为您使用的是布尔值。

当内部条件解析为 false 时,它​​显然会抛出错误,因为那时方法 returns undefined 因此调用 undefined.then(... 会引发错误。

当然,我不知道 checkIfDataLoaded() 到底应该做什么,但是如果你想将 .then() 链接到它的结果,那么它 总是 到 return 一个 Promise.

也许是这样的:

checkIfDataLoaded() {
    return new Promise((resolve, reject) => {
        if (this.homeLoaded && this.contactLoaded && this.aboutLoaded) {
            // Whatever logic goes here
            resolve(true);
        } else {
            resolve(false);
        }
    });
}

这样 checkIfDataLoaded() 总是 returns Promise 而它的内部可以做任何你需要的事情。