我有我在应用程序中使用的组件,并且在大多数情况下都可以正常工作。 它的 ts 文件如下所示:
import { Component, Input, OnInit, OnChanges } from '@angular/core';
import { Router } from '@angular/router';
import { LoadingService } from '@pyb-services/loading.service';
@Component({
selector: 'pyb-loading-button',
templateUrl: './loading-button.component.html',
styleUrls: ['./loading-button.component.scss']
})
export class LoadingButtonComponent implements OnInit, OnChanges {
@Input() link: any[] = []
@Input() target: string
@Input() navigateAfter: boolean
clicked: boolean = false
loading: boolean = false; // Has to be false by default, because sometimes everything has loaded before this button has come on the page
constructor(
private router: Router,
private loadingService: LoadingService
) {
}
ngOnInit() {
this.loadingService.onLoadingChanged.subscribe(isLoading => this.loading = isLoading);
}
ngOnChanges() {
this.navigateWhen();
}
click(): void {
this.clicked = !this.clicked;
this.navigateWhen();
}
private navigateWhen(): void {
if ((!this.loading || this.navigateAfter) && this.clicked && this.link.length) {
this.router.navigate(this.link);
this.clicked = false;
}
}
}
模板文件如下所示:
<button class="btn btn-xl btn-secondary" type="button" [disabled]="loading && !navigateAfter" (click)="click()" [scrollTo]="target"
offset="10" [ngSwitch]="loading">
<span class="spinner" *ngSwitchCase="true">
<span class="bounce1"></span>
<span class="bounce2"></span>
<span class="bounce3"></span>
</span>
<span *ngSwitchDefault>Next step</span>
</button>
就像我说的那样,它似乎工作正常。 但是,如果另一个进程启动了http请求,那么我会收到错误消息:
ExpressionChangedAfterItHaHasBeenCheckedError:检查表达式后,表达式已更改。先前的值:'ngSwitch:false'。当前值:“ ngSwitch:true”。
抱怨着加载按钮组件中的loading
属性发生了变化。
有谁知道我该如何解决?
答案 0 :(得分:0)
这是变量loading
的问题,已在触发更改检测时更改了该变量。为避免此错误,请在单独的线程中设置loading
的值。
ngOnInit() {
this.loadingService.onLoadingChanged.subscribe(isLoading =>
Promise.resolve(null).then(() => this.loading = isLoading)
);
}