Is there a way to switch on and off an ngrx action?

Here is a statement that triggers a load action to the store. The relevant effect will process the request and return the response items.

However, my goal is to be able to control this action with a button.

When I click on start, it should initiate dispatching actions every 1 second. If I click on pause, it should halt dispatching. When I click on start again, it should resume from where it stopped and continue in a loop...

How can I achieve this toggle functionality?

    let date = 1587513626000; // date is essential as the backend provides data with a start and end date
    interval(1000).pipe(tap(_ => {
      this.store.dispatch(loadStoreItems({ limit: 10, start: date, end: date + 1000 }))
      date += 1000
    }))
      .subscribe()

I have experimented with several operators, some of them work partially (such as utilizing takeWhile/takeUntil to pause at times) but I am struggling to restart the action.

Answer №1

To implement a toggle feature in an effect, you need to have two actions (start and stop) and utilize the takeUntil operator.

//effects.ts

  loadCourierItems$ = createEffect(() => 
    this.actions$.pipe(
      ofType(actions.start),
      exhaustMap(action => interval(1000).pipe(
        // logic for every second activity.
        map(actions.everySecondAction()),
      )),
      takeUntil(this.actions$.pipe(ofType(actions.stop))),
      repeat(),
    )
  )
//app.component.ts

  constructor(private store: Store<CourierItemsState>) {
  }

  ngOnInit() {
    this.store.dispatch(startAction());
  }

  ngOnDestroy() {
    this.store.dispatch(stopAction());
  }

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

Issue with character encoding in jQuery-ui tabs

Special characters in Swedish are replaced when configuring the tabTemplate option. For instance, using "ö" in the href attribute: var $tabs = $("#tabs").tabs('option', 'tabTemplate', '<li><a href="#ö">#{label}</ ...

"Troubleshooting an issue with ng-model not functioning properly with radio buttons in Angular

I'm a newcomer to Angular and I'm attempting to retrieve the value of the radio button selected by the user using ng-model. However, I'm not seeing any output in "selected contact". Check out My HTML below: <!doctype html> <html n ...

Tips for sending information to a nested Angular 2 attribute component

As per the instructions found on this blog, in order to create inner components within an SVG using Angular 2, we need to utilize an [attribute] selector: // Within svgmap.component.ts file: component declaration @Component({ selector: '[svgmap]& ...

What's the most effective method for identifying a pattern within a string of text?

For the sake of honing my skills, I undertook a practice task to identify patterns of varying lengths within a specified string. How can this function be enhanced? What potential issues should I address in terms of optimization? function searchPattern(p ...

Is there a compatibility issue between Nativescript and Angular Universal?

I am fairly new to Nativescript and recently attempted to incorporate Angular Universal building into an existing Angular 9/Nativescript application. However, I encountered the following error: [error] Error: Schematic "universal" not found in collect ...

The addition operator cannot be used with the Number type and the value of 1

Encountering an issue where the operator '+' cannot be applied to types 'Number' and '1' buildQuerySpec() { return { PageSize: this.paging.PageCount, CurrentPage: this.paging.PageIndex + 1, MaxSize: '' ...

The Correct Approach for Implementing Error Handling in a Node.js API Server

In my Node.js API server, I encountered an issue with error handling. To tackle this problem, I developed a module specifically for error handling. When in development mode, this module sends JSON objects containing errors to the API client. Here is an exa ...

Ways to access the scrollTop attribute during active user scrolling

I've been working on a website that utilizes AJAX to keep a chat section updated in real-time. One issue I encountered was ensuring the chat automatically scrolled to the bottom when a user sent a message, but remained scrollable while new messages we ...

Choosing a Component in a Collection with Angular 2

Seeking advice on how to address an issue I'm facing with a sign-up page. Within the page, there are two buttons, represented by components <btn-gender>, each displaying a gender option for selection. The challenge lies in creating a logic to d ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

Attempting to invoke a static function from a imported ES6 module

Currently, I am utilizing Firefox 56 with the setting dom.moduleScripts.enabled enabled. This configuration allows me to engage with native ES6 modules seamlessly. In my Vue2 component, there is a method that I have defined: import StorageZonesAjaxMethod ...

Can the MemoryRouter be successfully nested within the BrowserRouter in a React application?

I've been on a quest for some time now, trying to uncover whether it's feasible to utilize MemoryRouter solely for specific routes while maintaining the use of BrowserRouter in general. My goal is to navigate to a particular component without alt ...

Automate your workflow with Apps Script: Save time by appending a row and seamlessly including additional details to the

I currently have 2 server-side scripts that handle data from an html form. The first script saves user input to the last row available in my Google sheet, while the second script adds additional details to the newly created row. Although both scripts work ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...

Creating XML files using Node.js

What are some effective methods for generating XML files? Are there tools similar to the Builder in Rails, or any other recommended approaches? Appreciate any insights! ...

Tips for obtaining accurate response from axios

When utilizing axios, I receive my query response in the format of response.data.response.object. Is there a way to access the answer directly without going through response.data first? ...

Prevent JavaScript from sending a POST request to a specific URL

Currently facing Cross Site Scripting (XSS) vulnerabilities in a web application, I am curious if there are security measures equivalent to Content-Security-Policy: frame-ancestors and X-Frame-Options for JavaScript. My objective is to restrict the abilit ...

Monitor the change in values upon pressing the submit button on Angular

I am currently working with an edit form that contains data in the input fields. <ng-form #infoForm="ngForm" novalidate> <div> <label for="firstName">First Name :</label> <input type=" ...

approach for extracting values from nested objects using specified key

There are objects in my possession that contain various nested objects: let obj = { nestedObject: { key: value } } or let obj2 = { nestedObject2: { nestedObject3: { key2: value2 } } } and so on. Retrieving the values from these objects i ...

Angular unit tests do not trigger the QueryList.changes.subscribe() listener

I need to create popup containers based on the number of items received. The component works fine in dev and prod environments, but fails in unit tests because querylist.changes does not emit. As a workaround, I have to manually call querylist.notifyChange ...