ngIf值更改时未触发

时间:2018-10-09 08:00:56

标签: angular ngonchanges angular-changedetection

我有一个简单的mat-spinner,应该在isLoadingtrue时触发。变量将按预期更改,但看不到垫旋转器。仅当我将isLoading更改为始终为true时可见。

我想念什么吗? 预先感谢!

app.component.ts:

import { Component, OnDestroy } from '@angular/core';
import { UtilityService } from './services/utility.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnDestroy {
  title = 'cpt';

  isLoading = true;
  subscription;

  constructor(private utilityService: UtilityService) {
    this.subscription = this.utilityService.getIsLoadingObservable().subscribe(isLoading => {
      this.isLoading = isLoading;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

app.component.html:

<div class="loading-shade" *ngIf="isLoading">
  <mat-spinner></mat-spinner>
</div>
<app-router></app-router>

utility.service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UtilityService {

  public isLoading: BehaviorSubject<boolean> = new BehaviorSubject(false);

  constructor() { }

  getIsLoadingObservable(): Observable<boolean> {
    return this.isLoading.asObservable();
  }

  async setIsLoading(val: boolean) {
    await this.isLoading.next(val);
  }
}

EDIT触发setter函数的添加组件: start.component.ts:

import { Component } from '@angular/core';
import { NodeService } from '../../services/node.service';
import { UtilityService } from '../../services/utility.service';

@Component({
  selector: 'app-start',
  templateUrl: './start.component.html',
  styleUrls: ['./start.component.scss']
})
export class StartComponent {

  isLoading = false;

  constructor(
    private nodeService: NodeService,
    private utilityService: UtilityService) {}

    async selectNode(val: string) {
      await this.utilityService.setIsLoading(true);
      if (val === 'bank') {
        await this.nodeService.setNode('http://localhost:8091');
      } else if (val === 'auditor') {
        await this.nodeService.setNode('http://localhost:8092');
      } else if (val === 'spv') {
        await this.nodeService.setNode('http://localhost:8093');
      } else {
        await this.nodeService.setNode('http://localhost:8094');
      }
      await this.utilityService.setIsLoading(false);
  }
}

2 个答案:

答案 0 :(得分:0)

您的代码很好,可以按预期在此处工作。您必须手动运行WHERE Country__c="Netherlands"方法,如下所示:

setIsLoading()

答案 1 :(得分:0)

好吧,这与ngIf无关,对不起。问题在于setNode()函数,其中第二个setIsLoading()调用(返回false)是在第一次调用之后直接进行的,因为await无法正常工作。

感谢所有尝试提供帮助的人!