在装饰器中的功能原型中添加打字打字

时间:2018-10-17 02:19:01

标签: javascript angular typescript

我在如何将类型添加到Decorators的函数原型中时遇到问题。我要在组件类中存档的是,当此组件运行ngOnDestroy时,我想退订rxjs。它已经可以工作了,但是没有打字输入。

这是我的代码

// Component 
import { Component, OnInit } from '@angular/core';
import { debounceTime, filter, tap } from 'rxjs/operators';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UnsubscribeComponent } from '@app/helper/unsubsribe-component.helper';

@UnsubscribeComponent()
@Component({
  selector: 'app-modal-filter',
  templateUrl: './modal-filter.component.html',
})
export class ModalFilterComponent implements OnInit {

  public formFilter: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
  ) {
    this.formFilter = this.formBuilder.group({
      'startDate': [null, Validators.required],
      'endDate': [null, Validators.required]
    });
  }

  ngOnInit() {

    this.formFilter.valueChanges.pipe(
      // @ts-ignore  <- If i add this the warning will gone but i dont want to add this every rxjs later.
      this.unsubsribeOnDestroy,   // <- Error "Property of unsubsribeOnDestroy is not exist on type ModalFilterComponent"
      debounceTime(200),
      filter(_ => this.formFilter.valid),
    ).subscribe();
  }

}

这是我的Decorator函数UnsubscribeComponent

import { takeUntil } from 'rxjs/operators';
import { Observable, ReplaySubject } from 'rxjs';

export function UnsubscribeComponent(): ClassDecorator {
  const destroyed$: ReplaySubject<boolean> = new ReplaySubject(1);

  return function (componentClass: any) {
    const destroyHook = componentClass.prototype['ngOnDestroy'];

    componentClass.prototype['unsubsribeOnDestroy'] = (source: Observable<any>): Observable<any> =>
        source.pipe(takeUntil(destroyed$));

    componentClass.prototype['ngOnDestroy'] = () => {
      destroyed$.next(true);
      destroyed$.complete();

      // tslint:disable-next-line:no-unused-expression
      destroyHook && destroyHook();
    };
  };
}

谢谢

1 个答案:

答案 0 :(得分:0)

根据链接的the issue yurzui,TypeScript不支持更改类类型的类装饰器。我建议将UnsubscribeComponent逻辑放在可以从ModalFilterComponent而不是装饰器扩展的基类中。如果由于您希望组件扩展另一个类而导致问题,那么可以将取消订阅逻辑移至mix-in上,您可以将其应用于任何所需的基类,然后再在组件中扩展它。