2016-10-19 89 views
0

我最近開始學習Angular2概念,所以我有一個問題想了解如何使用。然後完成交易後改變ngOnOnit一個布爾「裝」值,我的組件從檢索數據服務完美。如果有人能夠給我一個手將是巨大的。更新變量Angular2

基本上就是我想要做的就是改變值裝載到「假」,並隱藏在完成循環後「MD-進步圈」。

這是我的HTML。

<span *ngIf="loading"> 
<md-progress-circle mode="indeterminate"></md-progress-circle> 
</span> 

這是我的組件類。



    import { Component, OnInit } from '@angular/core'; 
    import { Router } from '@angular/router'; 
    import { DemographicsService } from './app.service-http'; 
    import { Demographics } from './demographics'; 

    @Component({ 
     selector: 'app-data', 
     templateUrl: 'app/app.data.html', 
     styleUrls: ['app/app.data.css'] 
    }) 
    export class AppData implements OnInit { 

     demographics: Demographics[] = []; 
     loading: boolean = false; 

     constructor(
     private router: Router, 
     private demographicsService: DemographicsService) { 
     } 

     ngOnInit(): void { 
     this.loading = true; 
     this.demographicsService.getDemographics() 
      .then(demographics => this.demographics = demographics); 
     } 
    } 

添加這樣的事情裏面。然後

this.loader = false

回答

2

.then的第一個參數是執行一次得出結果的功能。只需添加另一行代碼,做你想做什麼:

this.demographicsService.getDemographics().then(
    demographics => { 
     this.demographics = demographics; 
     this.loading = false; 
    } 
); 

一件事看出來的:如果承諾被拒絕或如果發生異常,loading=false線將永遠不會被執行,應用程序將留在無限的裝載狀態。

爲了解決這個問題,你可能想在.finally塊來設定負載來代替。無論如何這個塊都得到執行:

this.demographicsService.getDemographics().then(
    demographics => this.demographics = demographics; 
).catch( 
    error => { /* TODO: handle the error*/ } 
).finally( 
    ()=>this.loading=false 
); 
+0

非常感謝,還在學習ES2015概念(箭頭函數),非常感謝。 – Dimitri

+0

@Dimitri歡迎您。我在答案中加了一點。 – BeetleJuice