簡體   English   中英

Angular 2 - * ngif在從oberservable subscribe進行變量更新時不刷新

[英]Angular 2 - *ngif not refreshing when variable update from oberservable subscribe

在html中我有警告只應在出現像thius這樣的錯誤狀態時顯示

<div class="alert alert-danger" *ngIf="error">
    <strong>Not saved!</strong> There was an error when saving the project. Please try again later.
</div>

這很好用。 但是當我從一個observable設置值時,ngIf沒有得到更新的值。

這里是簡化的代碼,它始終將錯誤設置為true以用於測試目的

export class createProjectComponent {
    constructor(private service:ProjectsService){

    }

    model = new myModel();
    error = false;
    submitForm(){    
        this.service.createProject(this.model).subscribe(i=>{
            this.error=true;
          }
    }

有什么樣的通知我必須觸發?

如果這可以解決您的問題,您可以嘗試:

constructor(private cdRef:ChangeDetectorRef) {}

submitForm(){    
    this.service.createProject(this.model).subscribe(i=>{
        this.error=true;
        this.cdRef.detectChanges();
    }
}

如果確實存在,則this.service.createProject(this.model)中會有一些代碼導致執行離開Angulars區域。

更新

你不需要這個,如果你使用()=>到處而不是function () ,如果不是像someFunc(mycallback)那樣通過名稱傳遞函數,而是使用someFunc(() => mycallback())someFunc(mycallback.bind(this))

發現錯誤。 this改變了。 在觀察中, this指向osbervable不再是組件。

所以我必須得到一個變量的組件引用,並將此引用的錯誤設置為true。

工作代碼如下所示:

var component = this;

this.service.createProject(this.model).subscribe(i=>{
                component.error = true;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM