Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Select() with parameter

Tags:

select

ngxs

UPDATE

As of @NGXS v3.1, they finally introduced arguments into @Selector().

https://www.ngxs.io/concepts/select#lazy-selectors

Examples from the DOCS

First, you define the @Selector "pandas"

@State<string[]>({
  name: 'animals',
  defaults: []
})

@Injectable()
export class ZooState {
  @Selector()
  static pandas(state: string[]) {
    return (type: string) => {
      return state.filter(s => s.indexOf('panda') > -1).filter(s => s.indexOf(type) > -1);
    };
  }
}

Then you just call it in your '.ts' file

import { Store } from '@ngxs/store';
import { map } from 'rxjs/operators';

@Component({ ... })
export class ZooComponent {
  babyPandas$: Observable<string[]>;

  constructor(private store: Store) {
    this.babyPandas$ = this.store
      .select(ZooState.pandas)
      .pipe(map(filterFn => filterFn('baby')));
  }
}

* From Old Post *

I am trying to create a custom @Select () to be able to drill down a particular tree and return the values dynamically. Getting either undefined or it's not making it (executing)

user.component.ts

const location = 'new york'
@Select(state => UserState.getUserLocationSlots(state, location)) slots$;

user.state.ts

@Selector() 
static getUserLocationSlots(state: UserStateModel, location: any) {
  console.log(state);
  console.log(location); // <-- expecting 'new york', but getting undefined
}
like image 958
Jose Avatar asked Jun 06 '26 15:06

Jose


1 Answers

You can achieve this by using crateSelector function from @ngxs/store

In your .state.ts file:

static getLocationSlots(location: string) {
    return createSelector([UserState], (state: string[) => {
        // logic for filtering your data
        // eg.: state.filter(element => element == location)
    })
}

In your .component.ts file:

@Select(UserState.getLocationSlots('new york')) slots$: Observable<any>

You can also check here for more details

like image 135
Ionita Bogdan Avatar answered Jun 08 '26 23:06

Ionita Bogdan