What sets 'rxjs/operators' apart from 'rxjs/add/operator/'?

Can someone explain the difference between using

import { map } from 'rxjs/operators';
and import 'rxjs/add/operator/map'; ?

This issue arises in my service method that handles user logins:

// import { map } from 'rxjs/operators'; // Causes runtime errors
import 'rxjs/add/operator/map'; // Works perfectly at runtime

  public login(username: string, password: string): Observable<any> {
    console.log('Sending login credentials to fetch a token');
    const credentials = { 'email': username, 'password': password };
    return this.httpService.postWithHeadersInResponse(URI_LOGIN, credentials)
      .map((response: HttpResponse<any>) => {
        const header = response.headers.get(this.authService.getHeaderName());
        const token = this.authService.extractTokenFromHeader(header);
        console.log('Token extracted from response header: ' + token);
        this.authService.setJwtTokenToLocalStorage(token);
      });
  }

Answer №1

One key distinction lies in utilizing rxjs/add/operator/map, where it alters the prototype of Observable, enabling chaining with the . (dot) operator:

this.httpService.postWithHeadersInResponse(URI_LOGIN, credentials)
  .map(...);

However, this method of employing operators has been deprecated. The current approach involves using rxjs/operators:

import { map } from 'rxjs/operators';
this.httpService.postWithHeadersInResponse(URI_LOGIN, credentials)
  .pipe(map(...));

Answer №2

RxJs has undergone changes in the public_api.ts file and file organization within the rxjs-project in a more recent version (likely 5.5+).

The updated, correct way to import now is:

import { map } from 'rxjs/operators'

The old way of importing will soon be deprecated or removed in a future version (rumored to be 7.0 according to a blog). Furthermore, the old method only functions with rxjs-compat in newer versions of RxJs.

It is expected that rxjs-compat will not be compatible anymore with RxJs version 7.0 (most likely).

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

utilize a modal button in Angular to showcase images

I am working on a project where I want to display images upon clicking a button. How can I set up the openModal() method to achieve this functionality? The images will be fetched from the assets directory and will change depending on the choice made (B1, ...

What exactly does bivarianceHack aim to achieve within TypeScript type systems?

As I went through the TypeScript types for React, I noticed a unique pattern involving a function declaration called bivarianceHack(): @types/react/index.d.ts type EventHandler<E extends SyntheticEvent<any>> = { bivarianceHack(event: E): void ...

Tips for creating a Bitbucket pipeline to deploy an Angular Universal application

I'm currently working on deploying my Angular universal app on a server using Bitbucket pipelines. The scripts I've written in bitbucket-pipelines.yml are as follows: pipelines: default: - step: name: Build app caches: ...

Tips for manually triggering change detection in Angular 2+

I am presenting a component with the following structure: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app', moduleId: module.id, template: ` <input [value]="a" (change)="onValidate ...

Looking for a way to notify users about page expiry with an Angular 5 service?

I have multiple pages each containing numerous forms. I am looking to develop a monitoring service for these forms. These forms are connected to data model objects with a high number of properties. I attempted to use the watchjs library to track changes in ...

Issue encountered when transitioning from Angular 8 to Angular 9: Value discrepancy at index 0

While updating my Angular project from version 8 to 9, I encountered an issue after following the update guide on update.angular.io and running npm update. When attempting to compile the website using ng serve, the following error occurred: ERROR in Faile ...

Issues with debuggers in Chrome and Firefox with AngularJS are causing frustration for developers

Currently, I am in the process of developing a hybrid application that combines AngularJS with Angular 8. As part of my testing procedure, I am attempting to debug the application. However, I have encountered an issue where the debuggers function properly ...

The canActivate: [AuthGuard] feature on the external router is not functioning as expected

I'm encountering an issue with my routing. I attempted to use the following code: const routes: Routes = [ { path: 'home', component: HomeComponent, canActivate: [AuthGuard], children: [ { path: 'events', component: Ev ...

Is it possible to reactivate a stripe subscription that has been previously canceled

Currently, I am working on incorporating the functionality of resuming cancelled Stripe subscriptions. To achieve this, I am referring to the comprehensive guide available at: https://stripe.com/docs/billing/subscriptions/canceling-pausing Here is my appr ...

Ways to retrieve a json file within Angular4

Seeking guidance on accessing the data.json file within my myservice.service.ts file. Any suggestions on how to accomplish this task? Overview of directory structure https://i.stack.imgur.com/WiQmB.png Sample code from myservice.service.ts file ht ...

"Encountered a type error with the authorization from the credentials provider

Challenge I find myself utilizing a lone CredentialsProvider in next-auth, but grappling with the approach to managing async authorize() alongside a customized user interface. The portrayal of the user interface within types/next-auth.d.ts reads as follo ...

Tips on how to verify if the Angular test with native elements has produced an error

Is there a way to detect errors in an Angular test that uses native elements? The test I am running is as follows: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { MikeComponent } from './mike.component&a ...

What is the best way to sequentially invoke an asynchronous function within an Observable method?

Presently, I have the following method: public classMethod( payload: Payload, ): Observable<Result> { const { targetProp } = payload; let target; return this.secondClass.secondClassMethod({ targetProp }).pipe( delayWhen(() ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...

Uncovering TypeScript's Type Inference Power Through the keyof Keyword

Recently, I encountered a situation where I needed to utilize an abstract class. export abstract class ABaseModel { public static isKeyOf<T>(propName: (keyof T)): string { return propName; } } Following that, I also created another class wh ...

No errors are being displayed with the React Hook Form using Zod and Material UI

Presenting my custom ProductInfoForm built using Material UI, react-hook-form with zod validations. However, I am encountering an issue: upon submitting the form, the data is displayed in the console as expected, but when intentionally triggering an error, ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

When deleting a row, the pagination feature in <mat-table> may encounter issues with the sticky

Struggling with a problem that I couldn't find a solution for online, so hoping to get some help here. I'm currently working on a dynamically-filled table where users can delete individual rows. The table has a sticky column and pagination, but I ...

"Retrieving an element from an array may result in a value of

While going through an array of objects in my Angular component class, I faced a strange issue where the properties kept showing up as undefined. The function responsible for this behavior looks like this: upload(): void { const { fileHandles, related ...

Re-evaluating information when the query parameter is modified?

While working on my angular 2 projects, I encountered an issue where I couldn't reload the page by changing the query parameters within the same URL. I am currently utilizing resolve to fetch data before loading the page. I am now striving to figure ...