2017-06-29 30 views
0

我在Angular 2項目中使用ng-spin-kitAngular 2 ng-spin-kit

在組件我有這樣的代碼:

loading: boolean; 

setTimeout(() => { this.loading = true }, 
    1000 
); 

,並在HTML我有這樣的:

<sk-fading-circle class="loader" [hidden]="loading"></sk-fading-circle> 

所以,我做了微調運行,但它只能運行於1000毫秒。

我需要微調運行,直到API的內容被加載。

我不知道setTimeout()是否是最好的方法。

有誰知道我該怎麼做?

UPDATE

這是服務

export class AppService { 

    endPoint = AppConstants; 
    handler = AppHandler; 

    constructor(private http: Http) {} 

    getCandidates() { 
    const headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    headers.append('Access-Control-Allow-Origin', '*'); 
    headers.append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); 

    return this.http.get(this.endPoint.API_ENDPOINT_GET_CANDIDATES, { 
     headers: headers 
    }) 
     .toPromise() 
     .then((res: Response) => { 
     const data = res.json(); 
     const allCandidate = []; 

     data.result.forEach((entry) => { 
      const candidate = new Candidate(); 

      candidate.college = entry.college; 
      candidate.cultural_fit = entry.cultural_fit; 
      candidate.email = entry.email; 
      candidate.graduation = entry.graduation; 
      candidate.logic_test = entry.logic_test; 
      candidate.mobile_phone = entry.mobile_phone; 
      candidate.name = entry.name; 

      allCandidate.push(candidate); 
     }); 
     return allCandidate; 
     }) 
     .catch(this.handler.handleError); 
    } 

} 
+0

您使用的觀測量你的API調用?如果是的話,這將是相當微不足道的做到這一點 – CozyAzure

+0

我沒有使用Observables,但我會改變它在項目 –

+0

更新您的問題與您的API的調用,我可以建議與Observables的解決方案 – crash

回答

1

這是我會怎麼做

loading: boolean = false; 
getCandidates() { 
    // ... 

    this.loading = true; 

    return this.http.get(this.endPoint.API_ENDPOINT_GET_CANDIDATES, { 
    headers: headers 
    }).map(res => res.json()) 
    .catch(this.handler.handleError) 
    .finally(() => this.loading = false) 
    .subscribe(res => { 
    // ... 
    }); 
} 
0

有可能的幾個選項,主要的有:

  1. 使用可觀察到的從您的API獲取數據(其中 已經是angular的HTTP的一部分),訂閱並將數據/錯誤恢復後的加載設置爲 false rieved
  2. 傳遞一個回調函數,當你完成時執行。
0

首先,你應該使用* ngIf這樣的:

<sk-fading-circle class="loader" *ngIf="loading"></sk-fading-circle> 

在組件使用

loading: boolean = true; 

如果你的API使用觀測量你的代碼應該看起來像:

this.api.subscribe(data => .... 
... 
() => {this.loading = false}); 

這會導致數據一載入,微調框就會被移除。