服务不刷新数组



所以我有一个数组的对象在服务,我从api中获取。我创建了一个方法,通过单击按钮来删除其中一个元素。它的工作原理,但为了网站刷新我需要重新加载它,它不应该是这样的。当我发送删除请求时,我会过滤数组,这样我就不必再次从API中获取数组。

deleteCustomer(id: number) {
this.tokenFromLS = `${localStorage.getItem('token')}`;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Basic ' + this.tokenFromLS,
}),
};
this.http
.delete<void>(`http://127.0.0.1:8080/api/customer/${id}`, httpOptions)
.subscribe(()=>
{
this.customerList = this.customerList.filter((v) => v.id != id);
});
}

在我的组件首先我删除资源,然后我刷新我的数组。在删除它并从Service中检索之后,它应该没有我删除的元素。当我对数组的大小进行log时,结果是0,但当我对数组的元素进行log时,结果是这个元素在这里。我不知道发生了什么事

export class GetCustomerListComponent implements OnInit {
constructor(private customerService: CustomerServiceService) {}
customerList: CustomerDto[] = this.customerService.getCustomerList();
ngOnInit(): void {}
deleteCustomer(id: number) {
this.customerService.deleteCustomer(id)
this.customerList = this.customerService.getCustomerList();
console.log(this.customerList.length);
}
}

应该从组件本身订阅,而不是从服务订阅。服务应该只包含api逻辑。

在服务中返回httpresponse,并在组件中订阅它。

最新更新