Angular - Can't sort the data when changing quaryParams

Viewed 31

In component.ts

export class TabsComponent implements OnInit {
  constructor(
    private store$: Store<UsersState>,
    private router: ActivatedRoute
  ) {}

  ngOnInit(): void {
    this.onFilterByIncome();
    this.router.queryParams.subscribe((params) => {
      const param = params['tab'];
      console.log(param);

      if (param === 0) {
        this.onFilterByIncome(); //dispatch metods
      }
      if (param === 1) {
        this.onFilterByOutcome();
      }
      if (param === 2) {
        this.onFilterByLoan();
      }
      if (param === 3) {
        this.onFilterByInvestment();
      }
    });
  }

//Like this
  onFilterByIncome() {
    this.store$.dispatch(new UsersFilterByIncomeAction());
  }

I need the data coming into the component to change when the params is changed.

I tried different ways, but it didn't work out for me. With such a code as now, it does not work for me.

1 Answers

The issue is that you are doing a strict equality comparison (using triple equals ===) between a string query param value and a number. An activated route query param value will always be a string because a URL is only ever a string.

const param: string = params['tab'];  <-- returns a string type, i.e. '0'.

if (param === 0) {. <-- strict equality check will not pass even if the param is '0'.
  this.onFilterByIncome();
}

You can fix this by updating your comparison value to also be a string type. (I'd recommend this fix)

if (param === '0') {
  this.onFilterByIncome();
}

or you can do a loose equality comparison by using a double equals. ==

if (param == 0) {
  this.onFilterByIncome();
}
Related