Anith
Anith

Reputation: 11

change a function to service from a component in angular

Angular2: I wrote a remove function in component.ts where I remove an item by id.

How to pass that function in the service class?

Here's a funciton code:

removeProduct(id: any,name:any) {
    let message='remove'
    let call = this.dialog.open(CartModelComponent, { data:{ message,name }});
    call.afterClosed().subscribe(result => {
      if (result === "confirm") {
        for (let i = 0; i <= this.Cart.length; i++) {
          if (this.Cart[i]?.id == id) {
            this.Cart.splice(i, 1);
          }
        }
        localStorage.setItem('local-store', JSON.stringify(this.Cart));
        this.findTotal()
        this.noContent()
      }
    })
}

Upvotes: 1

Views: 561

Answers (2)

Rapha&#235;l Balet
Rapha&#235;l Balet

Reputation: 8563

The value should be change directly in the service. Then you simply subscribe to this value in your component.ts using an observable.

Like always with observable, do not forget to unsubscribe to avoid memory leak

Here an example

// foo.service.ts
onCartChanged$: BehaviorSubject<any[]> = new BehaviorSubject(null)

// ...

removeProduct(id: number, string) {
  const message='remove'
  const call = this.dialog.open(CartModelComponent, { data:{ message,name }});
  call.afterClosed().subscribe(result => {
    if (result === "confirm") {
      for (let i = 0; i <= this.Cart.length; i++) {
        if (this.Cart[i]?.id == id) {
          this.Cart.splice(i, 1);
        }
      }
      localStorage.setItem('local-store', JSON.stringify(this.Cart));
      this.findTotal()
      this.noContent()
      this.onCartChanged$.next(this.Cart)
    }
  })
}
// foo.component.ts
private _unsubscribeAll: Subject<any> = new Subject()

constructor(private _fooService: FooService) {}

removeProduct(id: any,name:any) {
  this._fooService.removeProduct(id, name) // Or directly in your html but it then have to be public 
}

ngOnInit(): void {
  this._fooService.onCartChanged$
    .pipe(
      filter((event) => (event ? true : false)),
      takeUntil(this._unsubscribeAll), // Do not forget to unsubscribe
    )
    .subscribe((newCart) => {
      this.Cart = newCart
    })
}

ngOnDestroy(): void {
  this._unsubscribeAll.next()
  this._unsubscribeAll.complete()
}

Upvotes: 0

Hossam EL-Kashef
Hossam EL-Kashef

Reputation: 568

1- create a service by using Angular CLI

2- move your removeProduct function to this service and add an extra parameter which is the cart array

3- after doing your remove logic return this cart array

3- inject your service into the component

4- use the remove function from the service and pass the id, name, cart array

5- store or do what u want with that array u returned

Remember to move dialog service and modal component to your new service.

Hope that you need.

Upvotes: 1

Related Questions