rawkfist0215
rawkfist0215

Reputation: 1485

Proper import pattern for pipeable RxJs operators using Angular CLI/WebPack rollup

In Angular CLI versions <1.5.0 you could import your project's RxJs operators into a single file and use them throughout the application.

i.e.

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 { }


With the encouraged usage of the RxJs pipe operator the import examples are always within the individual module it's used in.

i.e.

...
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);
    }
  }
}


I'm wondering if there's still a way to import all of these operators and static methods into one place or if it's necessary to include the import into each Angular definition for the Module, Component, Service, Pipe, Directive, etc.

Upvotes: 2

Views: 1210

Answers (1)

rawkfist0215
rawkfist0215

Reputation: 1485

Members from the Angular CLI team replied and said that since the pipeable operators are functions they need to be imported into each file.

Upside: The application supports better tree-shaking leading to a smaller bundle size. Third party libraries won't dirty the Observable prototype. It also becomes much easier to create custom operators.

Downside: The operators used by the application need to be included on a per file basis instead of once for the entire app.

Upvotes: 1

Related Questions