Unable to access 'this' within a custom operator in RxJs

I developed a unique operator that utilizes the this keyword, but I am encountering an issue where it always returns undefined. Even though I used bind to pass this into the function.

My special operator

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

How to use my custom operator

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

Answer №1

Typically, a custom operator in rxjs is implemented like this:

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

  ...implementation logic...

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

It can also take arguments like this:

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

For more information on creating custom operators in rxjs, check out this informative link.

Answer №2

Make sure to pass the store parameter to the shouldLoadNewOptimizationData function to eliminate the need for constantly binding this:

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

Answer №3

Modify to arrow function syntax

const shouldLoadNewOptimizationData = () => {
    return filter(([param1,param2,param3]) => {
       // implement some logic here
       if(condition){
          this.store.dispatch()...
       }
    })
}

Answer №4

If you're looking to fully embrace Angular 15 without relying on things like 'this', decorators, ngmodules, constructors, and more.

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

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

It is not possible to assign a unique name to the custom attr() method

The code provided by someone else is working perfectly fine. However, when I try to rename the attr method, for example to attrx, I encounter an error. The error message I receive after renaming the method is: TypeError: arg.attrx is not a function Below ...

"There seems to be an issue with the KeyListener function in

The error I'm encountering is: index.html:12 Uncaught TypeError: Cannot read property 'addEventListener' of null I'm unsure about what went wrong. The intention behind the code was to store the result of the selected radio button into a ...

Utilizing ng-repeat to display a collection of Angular Highcharts charts

As I work on developing a KPI app using Angular JS, my goal is to establish a collection of charts. Each item in the list will display distinct values and feature a different chart type based on my Model. I am relying on the highcharts-ng directive for th ...

Navigating to the most recent item within ng-repeat (AngularJS or JavaScript)

I am working on a feature where posts are displayed using ng-repeat in a div, and users can enter new posts in an input box. The posts are sorted so that the latest one appears at the bottom. After adding a new post, I want to automatically scroll down t ...

Surge the PrimeNG DialogModule by integrating the CalendarModule to enhance its functionality

Looking for a way to create an Edit popup dialog that includes an input form in Angular2 using the PrimeNG widgets. I have encountered issues with the dynamic content of the dialog box as shown in the screenshot. https://i.sstatic.net/r3INA.png I attempt ...

Encountering errors while attempting to share files in a system built with Node.js, Express,

This snippet shows my Node.js code for connecting to a database using Mongoose const mongoose = require('mongoose'); function connectDB() { // Establishing Database connection mongoose.connect(process see your Naughty's you're sure ...

Removing an item from an array in Mongoose

I'm encountering an issue with removing an Object from an Array and I'm unsure of the correct way to use $pull for this action. Any help would be greatly appreciated! JSON data "accountId": "62efd8c008f424af397b415d", "l ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

`Must have content in file input in order to be saved to MongoDB`

When attempting to save a registry in MongoDB using Node.js, it seems that the operation fails if an image is not selected. I would like the inclusion of an image in this process to be optional, rather than mandatory. router.post("/", upload.single("image" ...

Getting the received payload in Angular 4+

I am currently working on a front-end module in Angular and I need to send data from my app to another application where the user is already logged in. The data will be sent via POST request in JSON format. My question is, how can I access this payload i ...

Is there a way to restrict the amount of user input that is allowed?

Is it possible to restrict the input quantity when using the built-in arrow icon in the text field, but not when typing manually? https://i.sstatic.net/jjogP.png <TextField variant="outlined" label="Quantity" onChan ...

Can Express POST / GET handlers accommodate the use of jQuery?

I created a simple Express server to retrieve data from an HTML form and make queries to OpenWeatherMap using that data: const { OpenWeatherAPI } = require("openweather-api-node"); const express = require("express"); const bodyParser = ...

Troubleshooting Problem with Padding in ion-content for Ionic Angular

I am currently developing my inaugural Ionic application. The initial template I utilized was the rudimentary sidemenu layout. $ ionic start myApp sidemenu Afterwards, I crafted a straightforward page featuring a list which appears as follows... <ion ...

Encountering a 404 error when using the NestJS GET function within the service and controller

I am facing an issue with creating simple GET logic. When I test it in Postman, I keep receiving a 404 error. books.service.ts contains the following basic logic: constructor( @InjectRepository(Books) private readonly booksRepo: Repository<Boo ...

How do I incorporate an external template in Mustache.js?

Welcome, I am a beginner in using Mustache.js. Below is the template and JS code that I have: var template = $('#pageTpl').html(); var html = Mustache.to_html(template, data); $('#sampleArea').html(html); Here is the template ...

Methods used on a server and methods used on a client-side application

In my ASP.NET application using C# 2.0, I have created objects for a database with properties that can be called natively or through a RESTful JSON API. These objects are used to convert data into HTML for display on the website. On the site, there are se ...

Is there a way to capture the input from the text box and store it in the local storage?

I'm confused about why the data entered into the input box is not being saved to local storage. <body> <input id="name"> <button onclick="bob()"> save </button> </body> <script> const user = document.getElementByI ...

Troubleshooting Async Issues in Node.js

I am encountering an issue with my node.js app structure, which is as follows: async.forever( function(callback) { async.series([ function(callback) { SomeFunction1(function(err, results) { if (err) callback(err); ...

Trigger Vue method when the size of a div element changes

Is there a way to trigger a method every time the dimensions (width or height) of a div element change? <template> <div> </div> </template> <script> export default { methods: { updateSize() { // ...

encasing a snippet of code within a customized hyperlink

Here's the following "embed code" for an Instagram photo featuring Kim Kardashian. I'm curious - how can one encapsulate this embed code within an <a> tag (or another tag) so that clicking on the image will redirect to www.google.com? < ...