angularngxsangular-state-managmement

Angular - NGXS problem with loading data before view


Have you encountered a problem when you route to component and loading a table. But table is empty without data.

I mean the component / table is displayed. Data as i can see are in state(seassion storage] and loaded. I am able to display them if i refresh the page.

By the way i could dispatch state before this component and my problem could be solved or use simple service with call on api. But this is not solution for me.

So my problem is = how could i display / load data before view?

My assets.state.ts

    @Action(SetDevice)
  async setDevice({ patchState, dispatch }: StateContext<DeviceDataModel>) {
    return await this.deviceListService.getData().subscribe((response: DeviceDataModel) => {
      console.log(response);
      patchState({
        data: response.data,
        dataSet: response.dataSet,
        offset: response.offset,
        size: response.size,
      });
      dispatch(new SetDeviceSuccess());
    });
  }

Component - set data into state and load them into table some.component.ts

ngOnInit(): void {
    this.store.dispatch(new SetDevice());
    this.getTableData();
  }

getTableData() {
    this.tableData = this.store.selectSnapshot(DeviceState.getDataDevice);
  }

some.component.html

 <dynamic-table
        style="width: 85%;"
        *ngIf="tableData"
        [tableData]="tableData.data"
        [tableColumns]="tableCols"
        [url]="'devicelist'"
      ></dynamic-table>

Thank you in advance for any help or idea.


Solution

  • I resolve this issue with toPromise() and then(). I know its not a best aproceh. But now its working.

    So I simply replace this code with code below.

       ngOnInit(): void {
        this.store.dispatch(new SetDevice());
        this.getTableData();
      }
    
    getTableData() {
        this.tableData = this.store.selectSnapshot(DeviceState.getDataDevice);
    
      }
    

    First of all I display spinner and after receiving data I just hide spinner and display table thanks to .then()

     ngOnInit(): void {
         this.store
          .dispatch(new SetAccount())
          .toPromise()
          .then((result) => {
           console.log(res);
           this.getTableData();
          });
    }