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

Error: ngModel does not reflect dynamic changes in value

After calling a Spring service, I am receiving JSON data which is stored in the "etapaData" variable. 0: id: 266 aplicacao: {id: 192, nome: "Sistema de Cadastro", checked: false} erro: {id: 220, nome: "Falta de orçamento", checked: false} perfil: {id: 8, ...

Uploading Multipart Files and JSON Data using Spring Boot

I am looking to create an API using Spring Boot for uploading a multipart file as part of the JSON body, and also to save the image URL in a database. The requests will have the following format: ------WebKitFormBoundarynBsAcX7rJhOGsmfY Content-Dispositio ...

When employing Observables within Express Routing Middleware, setting headers may occur after they have already been transmitted

Working with Observable (specifically using Rxhttp) and connect-timeout to handle long running requests has been presenting a challenge. Despite hitting the error handling middleware, the .subscribe function continues to run, leading to errors like: Err ...

Observing the World with TypeScript

Sorry, I am quite new to this and facing a bit of confusion. So, I have a CalendarService which includes a method called getYear(id: string). The structure of my Year model is as follows: export class Year { id: string; number: Number; months: ...

What is the best way to convert this tsc script into an npm script in package.json?

I am looking to execute the following script as an npm script: tsc src/*.tsc --outDir bin When I run this command directly in the terminal, it works as expected. However, when I add the exact same script to my package.json: { "scripts": { ...

TypeScript enum type encompassing all potential values

One thing I have learned is that keyof typeof <enum> will give us a type containing all the possible keys of an enum. For example, if we have enum Season{ WINTER = 'winter', SPRING = 'spring', SUMMER = 'summer', AUT ...

The function '() => Promise<T>' cannot be assigned to type 'Promise<T>'

Here is an interface I have: export interface ITreeViewItem { getChildren: Promise<ITreeViewItem[]>; ... Now, let's take a look at the implementation of it: export class MyClass implements ITreeViewItem { public async getChildren() ...

I am searching for the RowEnter and RowLeave events in a kendo-grid for Angular 2. Where can I find them

When using an ODATA bound Kendo UI Angular 2 table, I am facing the challenge of needing to save the data that a user edits inline on a per row basis instead of per cell. If only there were RowEnter and RowLeave events available for me to achieve this. Do ...

The functionality of Angular Custom Validation using Directive is experiencing issues within the ng-change event

I have created a custom validator using directives to validate email addresses. The validation is triggered by a method called on ng-change, but the validation only displays on the second change of the input. <textarea id="txtEmail" name=&qu ...

Wait for a minimum of X milliseconds using RxJS

I'm attempting to achieve a specific functionality using RxJS: Trigger an event Make an API call Upon receiving the API response, do one of the following: Wait for at least X milliseconds after triggering the event If X milliseconds have already p ...

What is the process for integrating Vue plugins into Vue TypeScript's template?

Seeking guidance on integrating Vue plugins into Vue TypeScript's template, for example with vue-webpack-typescript. Specifically interested in incorporating vue-meta. Included the following code in ./src/main.ts: import * as Meta from 'vue-me ...

Strategies for launching a website with NPM-managed JavaScript dependencies?

Currently, in the process of building a website with Angular2 and TypeScript, I adhered to the 'Getting started' guide from the official website. However, upon completion, I noticed that my node_modules directory is approximately 70MB in size. Th ...

What is the most effective method for distributing TypeScript functions that are used by services and span multiple components?

I have a set of TypeScript functions that are currently scattered across components. These functions are being duplicated unnecessarily, and I am looking for a way to centralize them so all components can access them without redundancies. Since these fun ...

The logout feature experiences a malfunction when invoked from the app.component.ts file

I have an authentication Service with a Logout() function implemented as shown below: export class AuthService { isAuthenticated = new BehaviorSubject(false); constructor(private router: Router) { } Logout() { console.log('Logout'); ...

Importing the isPropertyUpdated method in Angular 4

My challenge lies in utilizing the isPropertyUpdated function within Angular 4. However, I have encountered a roadblock as Angular 4 does not facilitate deep imports. An example of an import that fails to work on Angular 4 is: import {isPropertyUpdated} ...

Generating a Radio Button Label on-the-fly using Angular 8 with Typescript, HTML, and SCSS

Struggling with generating a radio button name dynamically? Looking to learn how to dynamically generate a radio button name in your HTML code? Check out the snippet below: <table> <td> <input type="radio" #radio [id]="inputId" ...

Encountering an issue while trying to load a file from an API due to difficulties in parsing it to

When trying to load an xlsx file from an API, I encountered an error because Angular automatically tries to parse the body as JSON. To resolve this issue, I found that specifying the response type directly in the request works: this.http.get(this.url + " ...

Tribal Code Typescript Compiler

Typescript is a great alternative to Javascript in my opinion, but it bothers me that it requires node.js as a dependency. Additionally, I find it frustrating that there seems to be only one compiler available for this language, and it's self-hosted. ...

Chrome Driver Protractor Angular 2 encountering issue with unclickable element

My issue is with clicking the second level menu options to expand to the third level. I have tried using browser.driver.manage().window().setSize(1280, 1024) in the before all section. Here is my code snippet: it('Should trigger the expansion of the ...

The property 'class' is required for ".builders['browser']"

Upon successfully installing the dependencies using npm install, I encountered an error while attempting to run the server: Schema validation failed with the following errors: Data path ".builders['browser']" should have required property ' ...