Home > Back-end >  RxJs custom operator cant access 'this'
RxJs custom operator cant access 'this'

Time:12-16

I created a custom operator that access the this but it seems that it's always undefined, even though I passed to the function this with bind

custom operator

function shouldLoadNewOptimizationData() {
    return filter(function([p1,p2,p3]) {
       // some logic
       if(){
          this.store.dispatch()...
       }
    })
}

custom operator usage

effect = createEffect(()=> this.actions$.pipe(
    ofType(//action type),
    withLatestFrom(
        //...selectors
    ),
    shouldLoadNewOptimizationData().bind(this),
    // more operators..
    )
)

CodePudding user response:

Generally a rxjs custom operator is in the way

function myOperator<T>(source: Observable<T>) {

  ...some logic...

  return source; //or return source.pipe(....)
}

Or with arguments

function myOperator<T>(...args) {
  return function<T>(source: Observable<T>): Observable<T> {
    ..some logic..
    return source //or return source.pipe(....)
  };
}

See this great link about this

CodePudding user response:

Pass the store to shouldLoadNewOptimizationData. This way you avoid having to bind this every time you use the function:

function shouldLoadNewOptimizationData(store) {
    return filter(function([p1,p2,p3]) {
       // some logic
       if(){
          store.dispatch()... // -> use the provided store instead of `this.store`
       }
    })
}
effect = createEffect(()=> this.actions$.pipe(
    ofType(//action type),
    withLatestFrom(
        //...selectors
    ),
    shouldLoadNewOptimizationData(this.store),
    // more operators..
    
);

CodePudding user response:

Change to arrow function

function shouldLoadNewOptimizationData() {
    return filter(([p1,p2,p3]) => {
       // some logic
       if(){
          this.store.dispatch()...
       }
    })
}

CodePudding user response:

If you want to go full angular 15 (who needs this, decorators, ngmodules, constructors, ...)

import { Store } from '@ngrx/store';
...

const shouldLoadNewOptimizationData = () => {
    const store = inject(Store)

    return filter(([p1,p2,p3]) => {
       // some logic
       if(){
          store.dispatch()...
       }
    })
}
  • Related