我在如何将类型添加到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();
};
};
}
谢谢