What steps should I take to set up an automated polling system for real-time data updates in Angular?

Hello everyone, I am currently delving into the world of Angular and facing a challenge with refreshing service data automatically by making API requests at regular intervals. The focus is on a particular service where I aim to update the shopPreferences field based on a specified timer:

@Injectable({ providedIn: 'root' })
export class ShopManagerService {
    private shopPreferences: ShopPreferences = null;

    setPreferences(shopPreferences: ShopPreferences) {
        this.shopPreferences = shopPreferences;
    }

    isDeliverySlotsActive(){
        if(this.shopPreferences == null || this.shopPreferences.delivery_slots == null) return;
        return this.shopPreferences.delivery_slots;
    }

    getCurrencySymbol(){
       if(this.shopPreferences == null || this.shopPreferences.currency_display_symbol == null) return;
       return this.shopPreferences.currency_display_symbol;
    }
    ...
    // more data getters
}

Currently, the shopPreferences field gets initialized in a specific component using a separate ApiManagerService. Here's how it looks:

@Injectable({ providedIn: 'root' })
export class ApiManagerService {

    private token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MjcwMjA3MiwidGltZXN0YW1wIjoiMjAyMS0wNC0wOSAwOToxNToxNS4';

    constructor(private http: HttpClient) {}

    fetchShopPreferences(id: string) {
        const url = "https://commerce.ww-api.com/commerceapi/v1/front/front_url/" + id + "/";
        return this.http
            .get<ShopPreferences>(url, {
                headers: new HttpHeaders({
                    token: this.token,
                }),
            });
    }
    ...
    // more api requests
}

I'm seeking advice on how to refactor my code so that the ShopManagerService can handle the API request and keep the shopPreferences object updated at scheduled intervals - let's say every 2 minutes. Any suggestions or solutions would be greatly appreciated!

Answer №1

Consider implementing this approach instead, by eliminating the current call to fetchShopPreferences. Make sure to set the id property for the interval or provide it directly as an argument:

@Injectable({ providedIn: 'root' })
export class ApiManagerService {

    private token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MjcwMjA3MiwidGltZXN0YW1wIjoiMjAyMS0wNC0wOSAwOToxNToxNS4';

    public id: string; // Modify this when necessary

    constructor(private http: HttpClient, private shopManagerService: ShopManagerService) {
      interval(120000).pipe(
        switchMap(() => fetchShopPreferences(this.id).pipe(
          first())
        )
      )
      .subscribe((res) {
        shopManagerService.setPreferences(res);
      });
    }

    fetchShopPreferences(id: string) {
        const url = "https://commerce.ww-api.com/commerceapi/v1/front/front_url/" + id + "/";
        return this.http
            .get<ShopPreferences>(url, {
                headers: new HttpHeaders({
                    token: this.token,
                }),
            });
    }
    ...
    // more api requests
}

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

What would be a colloquial method to retrieve the ultimate result from the iterator function?

I've got a rather complex function that describes an iterative process. It goes something like this (I have lots of code not relevant to the question): function* functionName( config: Config, poolSize: number ): Generator<[State, Step], boo ...

Is it possible for us to customize the angular material chip design to be in a rectangular shape

I recently implemented angular material chips as tags, but I was wondering if it's possible to customize the default circular design to a rectangle using CSS? ...

Angular 8: ISSUE TypeError: Unable to access the 'invalid' property of an undefined variable

Can someone please explain the meaning of this error message? I'm new to Angular and currently using Angular 8. This error is appearing on my console. ERROR TypeError: Cannot read property 'invalid' of undefined at Object.eval [as updat ...

The Output() function seems to be failing to emit the event

My architecture setup is as follows: UiControlsModule |- Component 1 |- Component 2 The first module is imported and exported in SharedModule. CasesModule |- CaseListComponent |- // other components here SharedModule is also imported into CasesModule. ...

How do I disable split panel on Ionic 2 login page exclusively?

I have successfully implemented the split-pane feature in my app.html file. However, I am facing an issue where the split pane is being applied to every page such as login and SignUp. Can someone please guide me on how to restrict the split pane function ...

Using setTimeout or setInterval for polling in JavaScript can cause the browser to freeze due to its asynchronous

In order to receive newly created data records, I have developed a polling script. My goal is to schedule the call to happen every N seconds. I experimented with both setTimeout() and setInterval() functions to run the polling task asynchronously. However ...

How can I determine if an Angular library is compatible with the specific version of Angular that my application is utilizing?

My Angular 8 application is currently running on a version that's quite outdated compared to the latest release of Angular. When it comes to incorporating Angular libraries, how can I determine if they are compatible with Angular 8? Is there a strict ...

Angular pagination refers to the process of dividing a large

Currently utilizing ngx-pagination https://www.npmjs.com/package/ngx-pagination app.module: import { NgxPaginationModule } from 'ngx-pagination'; @NgModule({ declarations: [ AppComponent, ... ], imports: [ ... NgxPaginat ...

"Unfortunately, this container did not send out any hits" - Google Tag Manager

After successfully integrating Google Tag Manager into my Next.js website, here is the implemented code: import '../styles/global.css'; import type { AppProps } from 'next/app'; import Script from 'next/script'; import NextNP ...

Subscribing to a GraphQL mutation through Angular with the Appsync client

Currently, I am developing a chat application in Angular using GraphQL with Appsync on AWS. The current process for creating a new chat involves mocking up the chat and sending it to the server. On the server-side, a unique chat_id is generated for each ch ...

The bar chart functions perfectly on localhost but encounters issues after being hosted on Gitpage

Localhost Gitpage The bar chart was displaying correctly on localhost, but once it was hosted on Gitpage, it began to show issues. Any suggestions on how to resolve this? Repository Link: https://github.com/mzs21/bar-chart Live Preview: ...

Persistent notification that just won't disappear

I've been working on improving my Notification Component in React. import React, { useEffect, useState } from "react"; import { IoMdClose } from "react-icons/io"; export type NotificationValueType = { message: string; type: & ...

Leverage the power of the async pipe with ngFor on an Observable containing Observables within Angular

I have a variable defined in this way: myVar: Observable<Observable<MyObject>[]>. I am utilizing an Angular4 feature to iterate using the async pipe *ngFor="let obsMyObject of (myVar | async)" Currently, I have an Observable of MyObject, but ...

Guide to developing a universal store extension

I've been attempting to create a reactive global $store object using a plugin, but so far I have not been successful in getting it to function as intended. store.ts: import {reactive} from "vue"; export default { install: (app:any, opt ...

Sending a Nan alert regarding a JSON attribute

I recently completed a project using Angular4 that involves connecting to a nodeExpressJS server to retrieve JSON data and update the object with new information. Below is the onSubmit function from the addemployeeform. onSubmit(formValue: any) { cons ...

Navigating through multiple pages in Angular2 with Rails5

Typically, in Rails development, I would use will_paginate and be done with it. However, my current project involves using Rails5 solely as an API, while the front-end is entirely Angular2. I've explored NG Bootstrap4's Pagination, but I'm ...

Exploring cutting-edge Angular 2 UI controls?

Imagine this scenario: An extensive organization is in need of developing a large web application with advanced UI components, such as hierarchical grid/tree and charts, alongside the standard UI elements. All these controls should ideally be sourced fro ...

What are the steps to troubleshoot a Node Package Manager library in Visual Studio Code?

I have created a Typescript library that I plan to use in various NodeJS projects. The source code is included in the NPM package, so when I install it in my projects, the source also gets added to the node_modules folder. Now, during debugging, I want to ...

Tips for dynamically incorporating filtered selections into a Mat-Select dropdown

I am seeking guidance on how to prevent changing the values of already selected values in other rows when each row of the formArray is altered. Adding controls dynamically and correctly retrieving values in filters are functioning properly. The issue arise ...

A unique column in the Foundry system that utilizes function-backed technology to calculate the monthly usage of engines over a

In my dataset of ‘Engine Hours’, I have the following information: Engine# Date Recorded Hours ABC123 Jan 21, 2024 9,171 ABC123 Dec 13, 2023 9,009 ABC123 Oct 6, 2023 8,936 XYZ456 Jan 8, 2024 5,543 XYZ456 Nov 1, 2023 4,998 XYZ456 Oct 1 ...