简体   繁体   English

在 Angular 库中导出自定义 RxJS 运算符

[英]Exporting a custom RxJS operator in an Angular library

The following custom RxJS operator (actually just a .filter equivalent for demonstration) is currently declared in an Angular 4.0.0-rc.2 component.以下自定义 RxJS 操作符(实际上只是演示的 .filter 等效项)目前在 Angular 4.0.0-rc.2 组件中声明。

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?如何从该库中正确导出原型扩展和模块声明?

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/... .如果操作符不是库本身使用的,而是为了方便用户而存在的,它可以遵循 RxJS 与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运算符定义可以移动到包根目录中的一个单独文件( restrictToCommandOperator.jsrestrictToCommandOperator.d.ts )并像这样导入

import 'packagename/restrictToCommandOperator';

It should be noted that this will work smoothly only if the package doesn't have rxjs dependency with version restrictions.应该注意的是,只有当包没有版本限制的rxjs依赖项时,这才会顺利运行。 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 .如果是这样,则每个用户的项目可能有多个 RxJS 包版本,并且restrictToCommandOperator不会扩展所需的Observable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM