[英]Angular 2 View will not update after variable change in subscribe
我有一個問題,當我在可觀察訂閱中更新我的變量時,我的視圖不會改變。 我試圖在等待后端響應時顯示加載微調器,然后顯示響應,但微調器不會隱藏。 我的訂閱是這樣的:
this.isRequesting = "true";
this.questionService.onSubmit(form, this.questions).subscribe( (value) => {
this._ngZone.run( () => {
this.fileLocation = JSON.stringify(value);
console.log(this.fileLocation);
this.isRequesting = "false";
console.log(this.isRequesting);
});
});
我的這個組件的 html 看起來像這樣:
<spinner *ngIf="isRequesting=='true'"></spinner>
從后端(Springboot)得到響應后,我可以在控制台中看到 isRequesting 更改為“false”,但視圖仍然沒有改變。 微調器來自SpinKit ,我修改了本教程以使我的微調器工作。
我試過:
有沒有人對如何讓我的視圖更新或在我收到后端響應后以任何方式讓我的微調器隱藏有任何想法?
你在控制台上看到任何錯誤嗎? 這可能是因為在您對值進行更新后,angular 沒有運行更改檢測。 我認為您不需要ngZone.run
因為它會在角度區域之外運行代碼。
this.questionService.onSubmit(form, this.questions).subscribe( (value) => {
this.fileLocation = JSON.stringify(value);
console.log(this.fileLocation);
this.isRequesting = "false";
console.log(this.isRequesting);
});
如果由於某種原因您需要在 Angular 區域之外運行這個,那么您應該通知 angular 通過此方法中的任何一種運行更改檢測周期。
只需在設置的超時時間內包裝 isRequesting 的更新
setTimeout( () => this.isRequesting = "false", 0);
手動調用變更檢測
import {ChangeDetectorRef} from '@angular/core' constructor(private ref: ChangeDetectorRef){} this.questionService.onSubmit(form, this.questions).subscribe( (value)=> { //existing code console.log(this.isRequesting); this.ref.detectChanges(); });
您也可以嘗試此解決方案: 來自 Thoughtram 的指南
簡短版本:
import { ChangeDetectorRef } from '@angular/core';
...
constructor(private cd: ChangeDetectorRef) {}
...
... .subscribe( () => {
<yourstuff>
this.cd.markForCheck();
}
你很好。
背景:通過 .subscribe() 更改值時,angular 不會通知它應該運行 changedetection。 所以你需要自己運行它。
您可以通過 changeDetection 切換(開/關)模板更新。 您必須將您選擇的策略放入組件定義中。 您可以選擇默認或 OnPush 策略。
@Component({
selector: '...............',
templateUrl: '.......html',
styleUrls: ['..........scss'],
changeDetection: ChangeDetectionStrategy.Default
})
如果您在表達式*ngIf
中使用它,請記住*ngIf = false
將無法用作您需要添加的表達式
<ul *ngIf=" somefunction(x) ? false: true">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.