Can you provide instructions on how to use RXJS Observables to conduct a service poll?

If I want the get request to "api/foobar" to repeat every 500 milliseconds, how can I modify the code provided below?

import {Observable} from "RxJS/Rx";
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";

@Injectable() export class ExampleService {
    constructor(private http: Http) { }

    getFooBars(onNext: (fooBars: FooBar[]) => void) {
        this.get("api/foobar")
            .map(response => <FooBar[]>reponse.json())
            .subscribe(onNext,
                   error => 
                   console.log("An error occurred when requesting api/foobar.", error));
    }
}

Answer №1

Ensure that you have correctly imported {Observable} from rxjs/Rx. Failure to import this may result in an 'observable not found' error at times.

View the functional plnkr example here: http://plnkr.co/edit/vMvnQW?p=preview

import {Component} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'app',
    template: `
      <b>Angular 2 HTTP polling every 5 sec RxJs Observables!</b>
      <ul>
        <li *ngFor="let doctor of doctors">{{doctor.name}}</li>
      </ul>

      `
})

export class MyApp {
  private doctors = [];
  pollingData: any;      

  constructor(http: Http) {
   this.pollingData = Observable.interval(5000)
    .switchMap(() => http.get('http://jsonplaceholder.typicode.com/users/')).map((data) => data.json())
        .subscribe((data) => {
          this.doctors=data; 
           console.log(data);// see console you get output every 5 sec
        });
  }

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

Answer №2

Give this a shot:

const fetchData = () => {
    return Observable.interval(2000)
        .switchMap(() => this.http.get(url).map(res:Response => res.json()));
}

Answer №3

Have you considered using setTimeout() instead?

setTimeout(fetchData(), 1000);

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

The module "<file path>/react-redux" does not contain an exported member named "Dispatch"

Currently, I am in the process of following a TypeScript-React-Starter tutorial and have encountered an issue while wrapping a component into a container named Hello.tsx. Specifically, at line 4, the code snippet is as follows: import {connect, Dispatch} ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

The operation of assigning the value to the property 'baseUrl' of an undefined object cannot be executed

I recently created a JavaScript client using NSWAG from an ASP .NET Rest API. However, I am encountering some errors when attempting to call an API method. The specific error message I am receiving is: TypeError: Cannot set property 'baseUrl' of ...

Guide on implementing ng2-completer with translation features

Recently delving into Angular, I'm experimenting with integrating the ng2-completer module alongside the TranslateModule. The issue arises when attempting to fetch JSON data from the server-side. The retrieved JSON structure is as follows: [{"id":10 ...

Does @angular/router have a similar function to ui-router's transition.from()?

I am currently in the process of updating an Angular application from ui-router to @angular/router (v6). There is a specific function that aims to retrieve the previous route. Below is the code snippet utilizing Transition from ui-router/core: const ...

Sorting Angular data using database queries

I'm currently setting up a blog for my website. Everything is running smoothly with the database, but I've run into an issue with the order of my posts - they are displayed in the opposite order that I want. The oldest post is showing at the top, ...

Serving Django and Angular with Apache

My setup involves using Angular for the frontend and Django Rest API for the backend. The structure of my project is as follows: example.com |- client (contains Angular files) |- server (contains Django Rest Framework files) The Angular app communica ...

Ways to selectively deactivate client-side functionality

I have implemented a server-side rendered app with transitions, including a 404 error page that I placed in a lazy module to avoid increasing the size of loaded JavaScript. While this setup is functioning correctly, there is some flickering when the clien ...

Setting checkbox values using patchValue in Angular programming

I'm facing an issue with reusing my create-form to edit the form values. The checkbox works fine when creating a form, but when I try to edit the form, the values don't get updated on the checkbox. Below is the code snippet that I have been worki ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

Show variously colored information for each selection from the dropdown using Angular Material

I am trying to change the color of displayed content based on user selection in an Angular application. Specifically, when a user chooses an option from a dropdown list, I want the displayed text to reflect their choice by changing colors. For example, i ...

What are the top tips for creating nested Express.js Queries effectively?

I'm currently exploring Express.js and tackling my initial endpoint creation to manage user registration. The first step involves verifying if the provided username or email address is already in use. After some investigation, I devised the following ...

Is the validator in my Angular reactive form malfunctioning?

I have been working on a service where I'm trying to validate the zip code field, but for some reason, the logic (result ? null : { IsInvalid: true }) is not executing. It makes me wonder if there's an issue with the reactive form or if I am usin ...

Could Angular be automatically applying margins or padding to my component?

I'm encountering a minor issue.. I'm attempting to create a "Matrix" to construct a snake game in angular, but there seems to be an unremovable margin/padding. Below is my code: <!-- snake.component.html --> <div id="ng-snake-main&q ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Typescript has a knack for uncovering non-existent errors

When I attempted to perform a save operation in MongoDB using Mongoose, the code I initially tried was not functioning as expected. Upon conducting a search online, I came across a solution that worked successfully; however, TypeScript continued to flag an ...

Error message: Module 'firebase/app' not found in angular framework

I am currently working through a Google codelab, which can be found at this link: Check out the codelab here However, when I attempt to build the project using 'ng build --prod', I encounter the following error: ERROR in node_modules/@angular ...

Error: Visual Studio unable to locate Firebase node module

After running the command npm install firebase --save in the root of my project folder, a firebase folder was successfully added to my node_modules directory and the packages.json file was updated accordingly. In addition to using typescript, I have an ap ...

The inclusion of Angular 2 router queryParams in the URL is not happening

I implemented an auth guard to protect certain pages of my web-app. In order to enable users to return to the page they intended to access, I tried adding queryParams to the URL during a redirect. Initially, the code below worked as expected. However, rece ...

Animating multiple elements in Angular 2 using a single function

Currently, I am delving into Angular and faced a challenge while attempting to create a toggle categories menu. Within my navbar component, I have an animation trigger set up as follows: trigger('slideCategory', [ state('opened&apo ...