Utilize Angular and RxJS to incorporate polling functionality

I am looking to incorporate polling into my Nativescript with Angular application. I want to continuously check the status of my backend server every second. Currently, I have a service set up as follows:

@Injectable()
export class StateService {
getStatus(): Observable<StateApp> {
        let headers = this.getHeaders();
        return this.http
            .get(BackendService.stateUrl, {
                headers: headers
            })
            .map(res => {
                return res.json() as StateApp
            })
            .catch(this.handleErrors);
}

Next, I would like to subscribe to this service and send requests to the server. In my component, I have written the following code:

IntervalObservable.create(1000).subscribe(() => {
            this.statusService.getStatus()
                .subscribe(
                (next) => {
                    this.state = next;
                };
        });

I attempted to implement a solution I found on Stack Overflow from nearly two years ago that addresses a similar issue (Angular2 http at an interval). However, certain methods mentioned in the post, such as IntervalObservable.takeWhile, no longer exist in rxjs version 5.4.3. So, I am curious about the best way to achieve the same result (i.e., getting the initial result without waiting one second and stopping requests when the component is destroyed).

Answer №1

If you want to implement polling, one way is to use the rxjs interval operator. By using this approach, you can execute the this.statusService.getStatus() line at 1-second intervals:

 this.subscription = Observable.interval(1000).startWith(1)
 .mergeMap(() => this.statusService.getStatus())
 .subscribe((next) => {
     this.state = next;
 })

Update: Adding startWith(1) will ensure that it is executed immediately without any delay before starting the 1-second interval executions. Hopefully, this aligns with your requirements.

Alternatively: Another method is to utilize the timer operator as shown below:

this.subscription = Observable.timer(0, 1000)
  .mergeMapTo(this.statusService.getStatus())
  .subscribe((next) => {
        this.state = next;
    }, (errRes)=>{
       console.log(errRes);
   });

In this alternative approach, the timer operator will trigger an immediate execution followed by subsequent executions every 1000 ms.

Remember to unsubscribe the Observable components in the ngOnDestroy lifecycle hook.

  ngOnDestroy(){
     this.subscription.unsubscribe();
  }

Also, ensure you import the necessary dependencies:

  import {Observable} from 'rxjs/Observable';
  import 'rxjs/add/operator/mergeMap';
  import 'rxjs/add/operator/startWith';
  import 'rxjs/add/operator/mergeMapTo';
  import 'rxjs/add/observable/timer';

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: Error message - Unhandled promise rejection: NodeInjector error - ControlContainer not found

I'm having trouble validating a form and encountering an error. I tried implementing the suggestions provided in the following threads without success: Getting error suddenly in Angular Error: NodeInjector: NOT_FOUND [ControlContainer] Using forms i ...

"Within Angular 2+, the attribute referenced is not recognized as a valid property, even though it is explicitly defined within the @Input

The main goal here is to increase the vertical pixel count. <spacer [height]="200"></spacer> Initially facing an issue where an error message states that height is not a recognized attribute of spacer. To address this problem, I set up the fo ...

Is it possible to implement typed metaprogramming in TypeScript?

I am in the process of developing a function that takes multiple keys and values as input and should return an object with those keys and their corresponding values. The value types should match the ones provided when calling the function. Currently, the ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

Retrieving automatically generated module

In my setup, there is a component that takes in some data and dynamically generates other components using ngx-charts. This specific part acts as the directive @Directive({ selector: '[ad-host]', }) export class PresentationDirective { c ...

Update the input value with the selected option from the dropdown menu in Angular

How can I dynamically set the value of an input field based on the selection from a dropdown menu in Angular using Reactive Forms? Below is my HTML code: <nb-card> <nb-card-header> Services </nb-card-header> <nb-card-body&g ...

Resolving TypeScript error when importing images statically in Next.js

In order to enhance the performance of images in my nextjs app, I am working on image optimization. However, I encountered an issue stating: Cannot find module '/images/homeBg.jpg' or its corresponding type declarations. The image is actually st ...

Unable to allocate FormArray

Just delved into learning Angular and encountered a snag. I am trying to add and remove textfields for a form, so I attempted the following code in my component.ts file: import {FormBuilder, FormGroup, FormArray } from '@angular/forms'; This is ...

Invoking a method of a component within a service class

Is there a way to call a function in the Component Class from an Injectable Class? INJECTABLE: Injectable() export class theInjected { constructor(private afAuth: AngularFireAuth, private googlePlus: GooglePlus, public alertCtrl: AlertController){ ...

special characters such as the dollar sign ($) and hyphen (-) are not functional in the context of regex within

Looking for a regex that allows alphabets, numbers, and specific special characters such as /$:-@. I tested the following regex pattern: "^[ A-Za-z0-9@.$/-:]*$" It seems to work fine in all scenarios except with the dollar sign ($) and hyphen (-) ...

What are the steps to passing props to a dynamically imported React component?

I'm currently working on a project using Next.js, React, and TypeScript. One of the challenges I faced was dynamically importing a React component into my page while setting ssr to false, as the component contains references to window. These window r ...

Encountering issues with loading Angular formControl

I've been going through an Angular tutorial on forms, which you can check out here. In my 'datasources.component.html' file, I have the following code: <form [formGroup]="queryForm"> <label>Query: <input type="text" formCont ...

Utilizing prerender.io with lazy loading in Angular 2: A comprehensive guide

As Angular Universal is not expected to be included in the CLI for some time, I've had to resort to using prerender.io in order to ensure proper SEO functionality. However, my tests have shown that there are issues with lazy loaded modules causing SEO ...

Contrasting characteristics of class members in JavaScript versus TypeScript

Typescript, a superset of Javascript, requires that Javascript code must function in Typescript. However, when attempting to create class members in a typescript file using the same approach as Javascript, an error is encountered. CODE :- script.ts (types ...

Utilizing Mongoose Schema Enums Alongside TypeScript Enums

In our Typescript-based NodeJs project utilizing Mongoose, we are seeking the right approach to define an enum field on a Mongoose schema that aligns with a Typescript enum. To illustrate, consider the following enum: enum StatusType { Approved = 1, ...

Resetting the value of a radio button input option to null using Angular2 ngModel

In my Angular2 application, I am attempting to implement radio button inputs using ngModel and value. The goal is to have three options: true, false, and null. However, I am struggling to assign a value of null to one of the inputs. Ideally, when nothing ...

When restarting the React application, CSS styles disappear from the page

While developing my React application, I encountered a problem with the CSS styling of the Select component from Material UI. Specifically, when I attempt to remove padding from the Select component, the padding is successfully removed. However, upon refre ...

How can I utilize Material-UI's DataGrid component to incorporate multiple layers of text within a single cell?

I'm having trouble displaying two separate lines of text in a single cell using Material-UI's datagrid component. Here is the code I have attempted: const columns: ColDef[] = [ { field: "name", headerNam ...

Issue with Typescript in react: JSX element lacks construct or call signatures

After upgrading TypeScript, I encountered the error mentioned above in one of my components. In that component's render method, I have the following code: render() { const Tag = props.link ? 'a' : 'div'; return ( < ...

In Typescript, the function is expected to return a string rather than using the syntax of `() -> string`

Currently, I am attempting to implement the following code snippet for browser detection. However, I am encountering an error in relation to browserData, which states: Type '{ browserName: () => string; browserVersion: string | null; operatingSys ...