2

The following custom RxJS operator (actually just a .filter equivalent for demonstration) is currently declared in an Angular 4.0.0-rc.2 component.

declare module 'rxjs/Observable' {
  interface Observable<T> {
    restrictToCommand<U>(f: (x: T) => U): Observable<U>;
  }
}

Observable.prototype.restrictToCommand = function (cmd) {
  return new Observable((observer) => {
    const obs = {
      next: (x) => {
        if (x.command === cmd) {
          observer.next(x);
        }
      },
      error: (err) => observer.error(err),
      complete: () => observer.complete()
    };
    return this.subscribe(obs);
  });
};

This works fine. However, I would like to extract this declaration to a library that is responsible for external communication. The main import of this library is a singleton service.

How to properly export the prototype extension and the module declaration from within that library?

4
  • It's not clear if the operator is already used by the library or just exists for convenience. Commented Mar 8, 2017 at 14:32
  • The library itself has no internal use for the operator, it is a convenience function meant for users that import the library. Commented Mar 8, 2017 at 14:33
  • Then follow the way that RxJS goes with rxjs/add/operator/... and provide restrictToCommandOperator.js in package root. Commented Mar 8, 2017 at 14:37
  • Thank you, that looks like a valid path. If you were to formulate an answer with a code example (for completeness sake) I'd probably accept it ;) Commented Mar 8, 2017 at 14:40

1 Answer 1

2

If the operator isn't used by the library itself and exists for user's convenience, it can follow the the way that RxJS goes with rxjs/add/operator/....

Operator definition can be moved to a separate file in package root (restrictToCommandOperator.js and restrictToCommandOperator.d.ts) and be imported like

import 'packagename/restrictToCommandOperator';

It should be noted that this will work smoothly only if the package doesn't have rxjs dependency with version restrictions. If it does, there's a chance that there may be multiple RxJS package versions per user's project, and restrictToCommandOperator won't extend desired Observable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.