The function Observable.timer in Angular rxjs is throwing an error when imported

Encountering an error in my Angular application that reads:

ERROR TypeError: rxjs_Observable__WEBPACK_IMPORTED_MODULE_4__.Observable.timer is not a function at SwitchMapSubscriber.project (hybrid.effect.ts:20) at SwitchMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/switchMap.js.SwitchMapSubscriber._next (switchMap.js:34) at SwitchMapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:38) at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at ScannedActionsSubject.push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next (Subject.js:47) at SafeSubscriber._next (store.js:332) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:195) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:133) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77)

Snippet of the code triggering this error:

import { Injectable } from '@angular/core';
import { Effect, Actions } from '@ngrx/effects';
import { of } from 'rxjs/observable/of';
import { map, catchError, switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable';
import **'rxjs/add/observable/timer';**

import * as hybridActions from '../actions/hybrid.action';
import { FleetStatusReportService } from '../../fleet-status-report.service';

@Injectable()
export class HybridEffects {
  constructor(
    private actions$: Actions,
    private fleetstatusreportService: FleetStatusReportService
  ) {}

  @Effect()
  loadHybrid$ = this.actions$.ofType(hybridActions.LOAD_HYBRID).pipe(
    switchMap(() => Observable.timer(0, 900000)),
    switchMap(() => {
      return this.fleetstatusreportService.getHybridPerformance().pipe(
        map(hybrid => new hybridActions.LoadHybridSuccess(hybrid)),
        catchError(error => of(new hybridActions.LoadHybridFail(error)))
      );
    })
  );
}

After researching online, it seems that the latest Angular version should use

**import 'rxjs/add/observable/timer';**

However, this solution doesn't work for me. Any guidance on how to resolve this issue would be appreciated.

Answer №1

If you're working with the latest version of Angular and RxJS 6, the approach needs to be adjusted as follows:

import { map, catchError, switchMap } from 'rxjs/operators';
import { Observable, of, timer } from 'rxjs';

loadHybrid$ = this.actions$.ofType(hybridActions.LOAD_HYBRID).pipe(
  switchMap(() => timer(0, 900000)),
  switchMap(() => {
    return this.fleetstatusreportService.getHybridPerformance().pipe(
      map(hybrid => new hybridActions.LoadHybridSuccess(hybrid)),
      catchError(error => of(new hybridActions.LoadHybridFail(error)))
    );
  })
);

In essence, there's no longer a need for monkey patching of the Observable. Instead, you should import the timer function from rxjs and utilize it in your code.

For more information on this change, refer to:

https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md

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 is the reason behind TS not using Symbols for enums?

When it comes to enums, ES6 symbols provide a great solution for avoiding collisions. Initially, I assumed that TypeScript's enum type used Symbols for enums if the target was set to 'es6', but it turns out it doesn't: enum Role {Emplo ...

Activate backdrop feature in offcanvas mode

When trying to open an offcanvas panel, I discovered that adding show to its class is necessary for it to open. However, this caused the backdrop feature to stop working, and now clicking outside the panel does not close it. Is there a way to achieve the p ...

Struggling with establishing connection logic between two database tables using Prisma and JavaScript

I'm facing a perplexing logic problem that is eluding my understanding. Within the context of using next-connect, I have a function designed to update an entry in the database: .put(async (req, res) => { const data = req.body; const { dob ...

Bidirectional data binding in Angular 2 for the class attribute

Utilizing twitter bootstrap tabs, I aim to monitor the application of the active class on the li tag as users switch between different tabs. My objective is to control tab activation through custom buttons by modifying the class attribute to activate direc ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

The failure of an Angular2 HTTP GET request with a header

Attempting to make a simple get request using angular2 http, like this: (including the token retrieved from a post to my api) let idToken = localStorage.getItem('id_token'); let authHeader = new Headers(); if (idToken) { authHeader.append(&a ...

I am looking for a guideline that permits me to restrict the use of a form validation tool

We have developed our own version of the Validators.required form-validator that comes with Angular 7, but now we need to switch to using CustomValidators.required. To enforce this change, we are considering banning the use of the old Validators.required b ...

NestJs Function yielding inconsistent results based on its calling location

There is a puzzling issue that I am unable to solve. I have stored priceHistories in memory within an array. Strangely, when I invoke a get method, the returned value varies depending on where the method is called from. This is the original property and m ...

What methods does VS Code use to display type errors in TypeScript given that TypeScript requires compilation?

TypeScript is a language known for being statically typed, giving it the ability to verify types during the compilation process and translate the code into JavaScript. Considering this, how is it possible for VS Code to detect type errors without the code ...

Exploring how to access and read the request body within Angular2

I'm managing a launcher platform for launching various Angular2 applications that I have ownership of, potentially across different domains. I am looking to send configuration details through the request body. Is there a way to send a POST request to ...

The message shown on items.map stating that parameter 'item' is implicitly assigned the type 'any'

Currently, I am delving into the world of Ionic React with Typescript by developing a basic app for personal use. My current challenge involves dynamically populating an IonSegment from an array. Here is the relevant code snippet: const [items, setItems] ...

A TypeScript interface creating a type with optional keys of various types while enforcing strict null checks

I am attempting to devise an interface in typescript that resembles the following: type MoveSpeed = "min" | "road" | "full"; interface Interval { min?: number, max?: number } interface CreepPlan { [partName: string] : Interval; move?: MoveSpe ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

What is the reason for user.id being set as a 'string' by default?

Currently, I am in the process of creating a Next Auth system using TypeScript, and I have encountered a type issue related to the 'user.id' data. This error is specifically happening in the callbacks section. The types of 'user.id' ar ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...

Develop a carousel component using Vue.js

I'm currently working on a dashboard that needs to display cards, but I'm running into an issue. I want only four cards visible at a time, and when you click the arrow, it should move just one step to the next card. For example, if cards 1-4 are ...

Is there a way to have my accordion adjust automatically?

I have developed a dynamic accordion component that populates its values from the parent component. However, I am facing an issue where each accordion does not respond individually to clicks. Whenever I click on any accordion, only the first one expands an ...

What is the best way to combine async/await with a custom Promise class implementation?

I've created a unique Promise class. How can I incorporate it with async/await? type Resolve<T> = (x: T | PromiseLike<T>) => void type Reject = (reason?: any) => void class CustomizedPromise<T> extends Promise<T> { ...

Handlebar files are not compatible with Typescript loading capabilities

I am encountering an issue with my directory structure as follows : src |- server |- myServer.ts |- views |- myView.hbs dist |- server |- myServer.js The problem lies in the fact that the dist folder does not have a views subfolder, where the J ...

Is there a way for me to retrieve a variable from the response of a service that was defined within the same class in Angular 4?

import {Component, OnInit} from '@angular/core'; import {LoginService} from "../../services/login.service"; import {LoginUser} from "../../services/model"; @Component({ selector: 'login-component', templateUrl: './login.component. ...