Best practice for importing pipeable RxJs operators in Angular CLI/WebPack rollup

In the earlier versions of Angular CLI, specifically those before 1.5.0, it was common practice to import all RxJs operators and statics into a single file for easy usage throughout the application.

For example:

rxjs-operators.ts

// Statics
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/range';
import 'rxjs/add/observable/concat';
import 'rxjs/add/observable/merge';
import 'rxjs/add/observable/empty';

// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
...

app.module.ts

// OPERATORS
import './rxjs-operators';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [...],
  providers: [...],
  schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


Nowadays, with the introduction of the RxJs pipe operator, it is recommended to import these operators directly within the specific module in which they are used.

For instance:

...
import { Observable } from 'rxjs/Observable';
import 'rxjs/util/pipe';
import { take, catchError  } from 'rxjs/operators';


@Injectable()
export class AccountDetailsResolver implements Resolve<AccountDetails> {
  constructor(private membersApi: MembersApiService,
              private router: Router,
              private navigationManager: NavigationManagerService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<AccountDetails> {
    if(route.paramMap.get('accountId')) {
      return this.membersApi.getBasicDetails(route.paramMap.get('accountId')).pipe(
        catchError(error => {
          this.navigationManager.navigateToDefaultScreen();
          return Observable.of(null);
        }),
        take(1)
      );
    } else {
      return Observable.of(null);
    }
  }
}


The question arises whether there is still a way to centralize the import of all operators and static methods or if it's now required to include the import statements individually in each Angular definition such as Module, Component, Service, Pipe, Directive, etc.

Answer №1

The Angular CLI team has addressed the issue by emphasizing that pipeable operators, being functions, must be imported into each individual file.

Advantage: This approach promotes better tree-shaking and results in a smaller bundle size. It prevents third-party libraries from cluttering the Observable prototype and simplifies the creation of custom operators.

Disadvantage: Every file in the application needs to include the necessary operators instead of just once for the entire app.

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

Injecting a component in Angular 2 using an HTML selector

When I tried to access a component created using a selector within some HTML, I misunderstood the hierarchical provider creation process. I thought providers would look for an existing instance and provide that when injected into another component. In my ...

Issue with Redis cache time-to-live not adhering to set expiration

I have encountered an issue while using IoRedis and DragonflyDB to implement rate limiting in my web application. Despite setting a TTL of 5 seconds for the keys in the Redis DB, sometimes they do not expire as expected. I am struggling to understand why t ...

"Introducing the new Next.Js 14 sidebar featuring a sleek hamburger menu

I am in the process of developing a chat application. Currently, I have a sidebar that displays existing conversations and I would like to make it responsive by implementing open and close functionalities for mobile devices. Here is the code snippet for m ...

Guide on displaying toaster notifications using promises in Angular 2

Hey everyone, I've encountered a problem with promises while handling a 500 internal server error. I have set up Promises to handle post and get services, but when catching the 500 response, I can't seem to display it in a toaster. Here's my ...

Creating a Custom Form Control in Angular 2 and Implementing Disable Feature

I have developed a unique custom control using ControlValueAccessor that combines an input[type=text] with a datepicker. While the template-driven forms accept it without any issues, the situation changes when implementing the model-driven approach (react ...

Validate if the translation file exists in ngx-translate

Is there a way to determine if a translation file exists for the language obtained from navigator.language using ngx-translate? I am looking to implement something similar to: if( isLanguageAvailable(navigator.language)) { this.translate.use(navigator.l ...

Grid layout with columns of equal width in Bootstrap

I'm currently working on creating a dashboard with Angular and Bootstrap 4. I've utilized the equal-width columns from https://getbootstrap.com/docs/4.0/layout/grid and it's functioning well. However, I'm facing an issue where if the lo ...

Can you achieve a union of strings and a single string?

Is there a way to create a type in TypeScript that can accept specific strings as well as any other string? type AcceptsWithString = | 'optionA' | 'optionB' | 'optionC' | string playground The goal here is to design a ty ...

remove a specific element from an array

Hey there! I'm attempting to remove only the keys from an array. Here's the initial array: {everyone: "everyone", random: "random", fast response time: "fast response time", less conversations: "less conversatio ...

Error message in TypeScript: A dynamic property name must be a valid type such as 'string', 'number', 'symbol', or 'any'

Attempting to utilize the computer property name feature in my TypeScript code: import {camelCase} from "lodash"; const camelizeKeys = (obj:any):any => { if (Array.isArray(obj)) { return obj.map(v => camelizeKeys(v)); } else if (ob ...

Enroll a nearby variable "Data" to an Observable belonging to a different Component within an Angular application

Looking to update the HTML view using *ngIf, depending on a local variable that should change based on an observable variable from a shared service. HTML <div class="login-container" *ngIf="!isAuthenticated"> TypeScript code for the same componen ...

Struggling to locate the ID linked to a specific ObjectId and encountering issues with the import function?

Can someone help me with this issue? Error Message: ERROR TypeError: answerID.equals is not a function I am unsure why I am getting this error. Here is the code snippet: import { ObjectId } from 'bson'; export class Person{ personID: Objec ...

Using NPM in combination with React and TypeScript to incorporate AMD modules

I am currently in the process of setting up a development environment for an application that is written in TypeScript using React. I already have existing TypeScript code that compiles to ES5 and AMD modules. My goal is to avoid any JavaScript transpilat ...

Simulate an HTTP request from a service class during a jasmine test

I initially believed that spying on services in Jasmine using the spyOn method and returning a value when the method is called was straightforward. However, it seems like my assumption may have been too simplistic? I intend to test the following action in ...

React JS and Webpack encountering issue 'Unable to locate module 'webpack-cli/bin/config-yargs'' while running 'npm run start'

I have recently embarked on creating a React JS project from scratch, utilizing Webpack to compile assets and aid in development. However, I am encountering some issues when attempting to execute "npm run start." Below is a snippet of my package.json file ...

Contrasting assign and modify operations on arrays

After spending 2 days searching for a bug in my angular2 project's service.ts file, I finally found it and fixed it. However, I'm still trying to understand why the working code behaves differently from the bugged one, as they appear identical to ...

What is the process for importing a .gltf/.glb model into a Three.js application?

After browsing through several related topics on SO, I'm still unable to find a solution to my current issue. The problem I'm facing is that the .glb model simply refuses to load. My Vue application utilizes webpack (specifically the Quasar frame ...

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

Navigating in Angular before receiving a response from HTTP request

I've encountered an issue with my Angular page. The signin process calls the "login" function on a remote API, but the GUI always redirects back to the signin page before receiving a response. Despite adding a timeout to the HTTP call, it seems that ...

Tips for resolving aliases in tsconfig.app.json when dealing with multiple source directories in WebStorm

When it comes to generating source files, I do things a bit differently and create some of them outside of the usual src directory. Here's how my structure looks: - project - generated - $ui-services some-other.service.ts - src - ...