Search code examples
angularstate-managementngxs

NGXS dispatch cancle http request from another menu


I have weird situation using NGXS for example I have 3 menus :

  1. Menu sales > call http get sales data > has unsubsribe function in ondestroy()
  2. Menu customer > call http get customer data > has unsubsribe function in ondestroy()
  3. Menu set default year => has dispatch() methode but no http request data

default year

       this.store.dispatch(new SetYear(
        {
            year:'2022'                
        }))   .subscribe(
            data => {
                console.log('success default year')
            },
            error => {
                console.log('error')

            }
        );

user.state.ts

     @Action(SetYear,{ cancelUncompleted: true })
     SetYear(ctx: StateContext<UserStateModel>, action: SetYear) {
        const state = ctx.getState();
        ctx.setState({
          ...state,
          users: [{
            ...state.users[0],
            ...action.payload
         }] 
       });
      }

First i go to sales menu, second go to customer menu, and last go to set default year menu and I default year with dispatch(), but http get sales and http get customer is called again. why this is happen? what is solution?


Solution

  • I have solution my problem. In sales and customer component in ngonInit() I read ngxs store and give value to variable and call http request

    customer.component.ts : methode ngOnInit()

    Before

     this.users$.subscribe(async(data) => {
             let idstore = data[0].idstore;
             this.getCustomers(idstore) // call http request
        })
    

    After

       this.users$.pipe(
            take(1) //=> code solution pipe+take
          ).subscribe(async(data) => {
             let idstore = data[0].idstore;
             this.getCustomers(idstore) // call http request
        })
    

    that is works perfectly