2016-09-22 61 views
1

我有一個表組件:Angular 2,我應該採取哪種方法來顯示加載指示?

@Component({ 
    moduleId: module.id, 
    selector: 'ag-table', 
    template: ` 
     <span *ngIf="isLoading">Loading</span> 
     <table class="table"> 
      rows loaded through @Input() rows; 
     </table> 
    ` 
}) 

然後,我有一個父組件:現在

@Component({ 
    moduleId: module.id, 
    selector: 'ag-page', 
    template: ` 
     <ag-table [rows]=rows></ag-table> 
    ` 
}) 

,在AG-頁,我需要從服務器獲取數據,所以我做通過服務的http請求,比方說page.service.ts。在這一刻,我想在我的ag表中顯示加載指示。

哪種方法最好?

  1. 使用@ViewChild通過ag-page獲取組件實例並將isLoading設置爲true?

  2. 創建一個table.service.ts,將它注入到TableComponent並使用observables來檢測數據何時加載。

  3. 另一個建議?

回答

2

您可以測試是否設置了輸入rows

@Component({ 
    moduleId: module.id, 
    selector: 'ag-table', 
    template: ` 
     <span *ngIf="!rows">Loading</span> 
     <table class="table"> 
      rows loaded through @Input() rows; 
     </table> 
    ` 
}) 
export class AgTable { 
    @Input() 
    rows:Row[]; 
} 

當應用程序啓動,ag-page沒有任何行,以便傳遞給ag-table變量rows是不確定的。因此測試!rows返回true並顯示您的加載範圍。

在異步加載結束時,ag-page用新值覆蓋其行。通過輸入綁定,行被賦予ag-table。所以測試!rows現在是錯誤的,加載跨度被刪除。

+0

有趣的是,它太簡單了,我想我只能以這些複雜的方式來做到這一點...當我在ag頁面中點擊刷新數據按鈕時,我需要設置this.rows = undefined;再次重複這個過程吧? –

+0

是的,如果你想添加一個刷新按鈕,你只需要'刪除this.rows'或'this.rows = null'或類似的東西。我只是意識到你可以做到這一點更容易(我已經做了編輯) –

+0

不要忘記驗證答案,如果它滿足你的需要。 –

相關問題