我有一个表,该表的数据是从api中获取的,并且正在使用ngfor显示该表,并使用索引i跟踪每个表行。
如果http请求未按顺序完成,则此逻辑将中断-首先出现的请求将是第一个完成的请求。 有没有更好的方法可以解决这个问题呢?
我的逻辑。
HTML模板
<tr *ngfor="let row of rows; let i=index;">
<td>
<div (click)="delete(i)">delete row></div>
<div *ngIf="deleting[i]=="true">Show Loader</div>
</td>
<tr>
打字稿
delete(index) {
//adding true to the specific index which was clicked to
show loader based on condition
this.deleting.splice(index, 0, true);
//keeps track of the sequence of clicked row
this.sequence.push(index);
callback function and api request to delete row() {
another call back function (){
//to fetch new data so that view updates after deletion
//after success response
//delete the value at that index and add null in its place
deleting.splice(this.sequence[0], 0);
deleting.splice(this.sequence[0], 0, null);
//first element is always the first one which was inserted update it
by deleting the first element.
sequence.splice(0,1);
}
}
}
答案 0 :(得分:-1)
您好,您可以处理订阅错误。这是我为您工作的示例:
this.ch_subs = this.ch_serv.getSignals().subscribe(
data => { console.log(data);},
error => { console.log('Error: ', error) },
() => {this.loading = false; });
}
祝你好运!
答案 1 :(得分:-1)
按顺序删除可能不是一个好主意,因为如果其中一个删除最终花了一段时间,那么以后所做的所有删除将永远不会显示。您已经注意到,另一个缺点是索引可以更改。当索引更改时,它可能会干扰showLoading并删除错误的值。
您可以更改几项,以使其与接收响应的顺序无关。假设该行的数据结构如下所示:
{
id: string,
name: string,
someOtherData: any
}
您可以添加一个跟踪其是否被删除的属性->
{
id: string,
name: string,
someOtherData: any,
isDeleting: boolean
}
然后更改删除功能,以接受要删除的行而不是索引(因为此行可以更改)。假设行是一个数组,一旦收到响应,就可以使用findIndex或lodash's findIndex获取当前索引,然后将其删除。您的删除方法将如下所示:
delete(row) {
row.isDeleting = true
// api request to delete row
// on success
row.isDeleting = false;
const index = _.findIndex(rows, row);
// delete the value at this index and add null in its place
}
然后将您的html更改如下:
<tr *ngfor="let row of rows;">
<td>
<div (click)="delete(row)">delete row></div>
<div *ngIf="row.isDeleting === true">Show Loader</div>
</td>
<tr>
如果由于更改不容易而不想更改数据结构,则必须确保检查该属性是否存在,然后检查其是否为真。然后,我上面显示的删除方法仍然可以使用:
<tr *ngfor="let row of rows;">
<td>
<div (click)="delete(row)">delete row></div>
<div *ngIf="!!row.isDeleting && row.isDeleting === true">Show Loader</div>
</td>
<tr>