2017-06-16 109 views
0

我目前正試圖將我的FrontEnd與我們的後端API連接起來。 我遇到了一個問題,我必須等待後端做出反應。angular4 - 異步數據加載 - 異步ngFor循環?

例如,當我刪除我的一個層時,它不會立即更新,當我調用getTiers() - 方法時,因此Im使用setTimeout(() => this.getTiers(), 500);爲API提供了一個機會來響應並獲取更新後的響應我的前臺。

如果沒有setTimeout,我必須重新加載頁面,然後才能看到更改,例如刪除其中一個層之後。

有沒有更好的方法,異步工作的東西? 我試圖用異步管的ngFor環(<div class="col-md-4" *ngFor="let tier of tiers | async ">),但是這給了我樓下的錯誤:

我this.tiers對象是這樣的:this.tiers

錯誤:

core.es5.js:1290 ERROR Error: Uncaught (in promise): Error: InvalidPipeArgument: '' for pipe 'AsyncPipe' 
Error: InvalidPipeArgument: '' for pipe 'AsyncPipe' 
    at invalidPipeArgumentError (http://localhost:3000/vendor.bundle.js:86006:12) [angular] 
    at AsyncPipe._selectStrategy (http://localhost:3000/vendor.bundle.js:86151:15) [angular] 
    at AsyncPipe._subscribe (http://localhost:3000/vendor.bundle.js:86137:31) [angular] 
    at AsyncPipe.transform (http://localhost:3000/vendor.bundle.js:86115:22) [angular] 
    at Object.View_PackagesComponent_0.co [as updateDirectives] (ng:///PackagesModule/PackagesComponent.ngfactory.js:787:66) [angular] 
    at Object.debugUpdateDirectives [as updateDirectives] (http://localhost:3000/vendor.bundle.js:13333:21) [angular] 
    at checkAndUpdateView (http://localhost:3000/vendor.bundle.js:12671:14) [angular] 
    at callViewAction (http://localhost:3000/vendor.bundle.js:13034:21) [angular] 
    at execComponentViewsAction (http://localhost:3000/vendor.bundle.js:12966:13) [angular] 
    at checkAndUpdateView (http://localhost:3000/vendor.bundle.js:12677:5) [angular] 
    at callWithDebugContext (http://localhost:3000/vendor.bundle.js:13733:42) [angular] 
    at Object.debugCheckAndUpdateView [as checkAndUpdateView] (http://localhost:3000/vendor.bundle.js:13273:12) [angular] 
    at ViewRef_.detectChanges (http://localhost:3000/vendor.bundle.js:10745:63) [angular] 
    at RouterOutlet.activateWith (http://localhost:3000/vendor.bundle.js:93091:42) [angular] 
    at ActivateRoutes.placeComponentIntoOutlet 

回答

2

我建議你從前端刪除層,然後處理後端。這將爲用戶提供更好的體驗,因爲他們不必等待服務器的響應。

deleteTier(tier) { 
    this.tiers = this.tiers.filter(t => t.id != tier.id); 
    this.tierService.deleteTier(tier.id) 
     .subscribe(
     (tiers) => console.log('success' + tiers), 
     (error) => console.log('Following error appeared: ' + error) 
    );} 

如果你在你的後端的錯誤,您可以隨時重新添加刪除的%1中訂閱的(error) =>方法。

+0

謝謝,沒有想到的方式 –

+0

什麼是最好的辦法,每次onInit沒有數據重新加載?應該有一種方法來存儲數據後,它加載一次? 截至目前,用戶必須等待每一次,在他的層被加載和顯示之前 –

+0

@nicowernli我認爲這個:'this.tiers = this.tiers.filter(t => t.id!= tier.id); '應該在​​'.subscribe()'裏面,否則即使服務器返回錯誤,該項目也會從'list'中移除。 – developer033