How to execute code inside method suscribe() before componant is init

312 views Asked by At

I am trying to make that a component which is subscribed to a Subject executes the code related to the change of state of the Subject before the component is initialized (ngOnInit ()). Here is the CartService:

 
.... import ....
@Injectable({
  providedIn: 'root'
})
 
export class CartService {
  public updateCartSubject = new Subject<any>();
  public cart: any;
  constructor() {
  }
 
  public updateCart(data) {
    this.cart = data;
    this.updateCartSubject.next(this.cart);
  }
....
}

Here is the CheckoutCartComponent :

.... import ....
export class CheckoutCartComponent implements OnInit, OnDestroy {
  public items = [];
  public coupons = [];
  public paliers = [];
  public paliers_available = [];
  public totals = {
    discount: {
      inc_tax: 0,
      exc_tax: 0
    },
    exc_tax: 0,
    inc_tax: 0,
    subtotal: {
      inc_tax: 0,
      exc_tax: 0
    }
  };
  public countries = [];
  public accept_terms = false;
  public coupon_code = '';
  public coupon_loading = false;
  public coupon_error = false;
  public coupon_success = false;
 
  cartSubscription: Subscription;
 
  constructor(private cartService: CartService) {}
 
  ngOnInit(): void {
    this.cartSubscription = this.cartService.updateCartSubject.subscribe((data) => {
      this.editData(data);
    });
  }
 
  public editData(cart){
    if (cart && cart.items && cart.totals) {
      this.items    = cart.items;
      this.coupons  = cart.coupons;
      this.paliers  = cart.paliers;
      this.paliers_available  = cart.paliers_available;
      this.totals   = cart.totals;
    } else {
      this.items    = [];
      this.coupons  = [];
      this.paliers  = [];
      this.totals   = {
        discount: {
          inc_tax: 0,
          exc_tax: 0
        },
        exc_tax: 0,
        inc_tax: 0,
        subtotal: {
          inc_tax: 0,
          exc_tax: 0
        }
      };
    }
  }
.....

The problem is that the updateCart() function is called in several components but until I am on the CheckoutCartComponent page the code in the suscribe() method is not executed.

Do you have a solution for this?

Thank you in advance, Killian

0

There are 0 answers