2017-06-16 111 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