Home > database >  Service doesnt refresh array
Service doesnt refresh array

Time:10-07

so I have array of objects in service which I fetch from api. I've made method to delete one of the emelements by clicking on button. It works, but in order for site to refresh I need to reload it and it shouldnt be this way. When I send delete request I filter array so that I dont have to fetch array again from 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);
      });
  }

In my component first I delete resource and then I refresh my array. After deleting it and retriving from Service it should be without element I deleted. When I log size of array it says 0, but when I log elements of array it says that element is there. I am confused of what is happening

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);
  }
}

CodePudding user response:

You should subscribe from the component itself and not from the service. Service should contain the api logic only.

Just return the httpresponse in the service and subscribe it inside the component.

  • Related