2017-04-24 32 views
0

我試圖在數據完全加載時在我的應用程序上顯示一個微調框。所以我所做的是訂閱Web服務調用。我有一個名爲IsBusy的變量,在我進行服務調用之前設置爲True。完成Web服務調用後,我將IsBusy設置爲false。Angular2 - NgIf無法從訂閱訪問我的變量

在我的html我使用這個IsBusy來顯示/隱藏我的微調。現在它根本不顯示微調。以下是我的html和typescript代碼。

<div id="surgeryRequestFormContainer" class="container-fluid"> 

     <div *ngIf="isBusy" class="loading"> 
      <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" /> 
     </div> 
    <div class="row"> 
       <div class="form-group col-sm-12"> 
        <button kendoButton (click)="btnPrevious()">Previous</button> 
        <button kendoButton (click)="btnNext()">Next</button> 
        <button kendoButton (click)="btnSaveForLater()">Save For Later</button> 

       </div> 
      </div> 

我研究之前發佈和閱讀的地方,我可能需要從'@角/核心'導入ChangeDetectorRef。我做到了這一點,並在我的構造函數中將ChangeDetectorRef實例化爲cd。

ngOnInit(): void { 


     this.isBusy = true; 
     console.log("before the subscribe " + this.isBusy); 

     this.route.params 
      .switchMap((params: Params) => this._RequestFormService.getRequestById(+params['id'])) 
      .subscribe(
      data => this.Model = data, 
      error => console.log("Error", error), 
      () => this.isBusy = false); 
     this.isBusy = false; 
     console.log(this.isBusy); 
     this.cd.detectChanges(); // marks path 

    } 

我不確定我需要做什麼才能顯示/隱藏我的微調器div標籤。

+1

將'this.isBusy = false'移動到您的訂閱「next」回調中(您當前正在執行'this.Model = data'。 –

+0

就像adam-beck說的那樣。與console.log外部回調:http://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2 – Alex

+1

可能的重複[我如何返回從angular2中的Observable/http/async調用的響應?](http://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable- HTTP的異步通話中angular2) – n00dl3

回答

1

發生什麼事是Observable鏈正在進行異步調用。所以基本上,代碼執行不會等待,並且在this.isBusy = true後幾乎立即調用鏈之後調用this.isBusy = false。之後才能完成對服務的呼叫。但是,就此而言,你的微調已經關閉了。

相反,你應該做的是移動你的觀察鏈內的調用。

this.isBusy = true; 

this.route.params 
    .switchMap((params: Params) => this._RequestFormService.getRequestById(+params['id'])) 
    .subscribe(
     data => { 
      this.Model = data; 
      this.isBusy = false; 
     }, 
     error => console.log("Error", error), 
     () => this.isBusy = false); 

如果您熟悉setTimeout這實質上就是您對代碼所做的工作。

console.log('setting the value to true'); 

setTimeout(function() { 
    console.log('setting the value to false'); 
}, 1000); 

console.log('setting the value to false'); 

不添加任何的混亂,但觀測量本質上並不同步。我不相信subscribe中的「終於」回調將在此處被調用,因爲Observable永遠不會「結束」。