因此,我有以下想法:我想描述一个函数,该函数将某个服务提供的RxJs Observable作为第一个参数,并将OnNext函数处理程序传递给订阅方法。
import { Observable } from 'rxjs';
export interface OnNextHandler<T> {
(value: T): void
}
export interface ServiceSubscriber<T> {
(providedObservable: Observable<T>, onNext: OnNextHandler<T>): void
}
上面的代码似乎可以工作,尽管在某些情况下TS不会给我一个错误(并且我希望这样做)。 例如:
@Component({
selector: 'app-notes-list',
templateUrl: './notes-list.component.html',
styleUrls: ['./notes-list.component.scss']
})
export class NotesListComponent implements OnInit, OnDestroy {
activeNotes: Note[] = [];
archivedNotes: Note[] = [];
private destroy$: Subject<boolean> = new Subject<boolean>();
constructor(
private notesService: NotesService
) { }
ngOnInit() {
const { active, archived } = this.notesService; // pull our observables from the service
this.subscribeTo(active, activeNotes => this.activeNotes = activeNotes);
this.subscribeTo(archived, archivedNotes => this.archivedNotes = archivedNotes);
}
ngOnDestroy(): void {
this.destroy$.next(true);
this.destroy$.unsubscribe();
}
private subscribeTo: ServiceSubscriber<Note[]> = (providedObservable$, onNext) => {
providedObservable$
.pipe(takeUntil(this.destroy$))
.subscribe(onNext)
}
}
这是Angular组件之一,我正在其中尝试通过subscribeTo
接口键入ServiceSubscriber
方法。第一个参数被检查:例如,当我们传递字符串而不是预期的Observable
时,但是第二个参数(onNext回调)可以接收任何函数作为其值(我希望它成为一个接受参数为键入T
并返回无)。
为了演示,如果我将ngOnInit
中的代码更改为类似这样的内容:
ngOnInit() {
const { active, archived } = this.notesService;
this.subscribeTo(active, activeNotes => activeNotes); // pay attention here on the 2nd arg
this.subscribeTo(archived, archivedNotes => archivedNotes); // and here as well
}
因此,现在回调将返回某些内容,而不是预期的结果。我在这里想念什么?当回调函数签名错误时如何接收错误?谢谢。
答案 0 :(得分:0)
您应该使用never
的形式输入退货:
export interface ServiceSubscriber<T> {
(providedObservable: Observable<T>, onNext: OnNextHandler<T>): never
}
我相信这应该可行。
答案 1 :(得分:-1)