我有一个angular2应用程序,其后端是在java中。我有一份客户名单。当我单击以删除客户时,客户将被删除,但列表不会更新。如果我手动刷新页面,则列表会更新。我尝试在delete方法的订阅中路由到列表组件,但这不起作用。
列表customers.component.html
<tr [class.warning]="customer.isDefault == 1" *ngFor="let customer of customers | orderBy:['firstName'] | search:searchCustomer.value;let serial = index">
<td>{{ serial+1 }}</td>
<td>{{ customer?.firstName+' '+customer?.lastName}}</td>
<td>{{ customer.email}}</td>
<td>{{ customer.mobileNumber}}</td>
<td>{{ customer.streetAddress}}</td>
<td>{{ customer.priceList?.name}}</td>
<td><a [routerLink]="['/loggedIn','customer','edit', customer.id ]"><i class="fa fa-edit fa-2x"></i></a></td>
<td><a (click)="delete(customer)"><i class="fa fa-trash-o fa-2x"></i></a></td>
</tr>
列表customers.component.ts
ngOnInit()
{
this.refreshCustomersList();
}
delete(customer)
{
this.userService.delete(customer.id)
.subscribe(
success=>
{
var index = this.customers.indexOf(customer, 0);
if (index > -1)
{
this.customers.splice(index, 1);
}
}
)
}
refreshCustomersList()
{
this._authHttp.get(
this.appService.getApiUrl() + "api/customer/list"
)
.map(res=>res.json())
.subscribe(
successResponse=>
{
this.customers = successResponse.data.customers;
},
() => console.log("Request Completed")
)
}
}
尝试在this.refreshCustomersList();
函数中调用delete
,如下所示:
delete(customer)
{
this.userService.delete(customer.id)
.subscribe(
success=>
{
var index = this.customers.indexOf(customer, 0);
if (index > -1)
{
this.customers.splice(index, 1);
this.refreshCustomersList();
}
}
)
}
这将在客户被删除后更新customers
阵列。
Splice将返回已删除的元素,而不是使用slice在删除后返回结果数组,如: -
this.customers = this.customers.slice(index);
我们可以按如下方式设置客户列表,而不是再次从API获取整个列表。它对我有用:
delete(customer)
{
this.userService.delete(customer.id)
.subscribe(
success=>
{
var index = this.customers.indexOf(customer, 0);
if (index > -1)
{
this.customers = this.customers.splice(index, 1);
}
}
)
}
在HTML中输入以下代码:
(click)="delete(customer.length-1-i)".
//
deleteFieldValue(index) {
this.customer.splice(index, 1);
this.revervefordispaly();
}
//for reverse:
revervefordispaly(){
this.reversedProductdata.reverse();
}
你可以像这样使用JavaScript数组过滤器。
this.userService.delete(customer.id)
.subscribe(
success=>
{
let newCustomers = this.customers.filter(item => item.id !== customer.id);
this.customers = newCustomers;
}
)