在一个Angular组件中,我有一个MatSelect
类型的子项,我可以通过以下代码获取它
@ViewChild('mySelect') mySelect: MatSelect;
我现在可以在代码中使用mySelect
来响应选择中的更改,例如像这样
this.mySelect.selectionChange
.pipe(
map(selChange => // here type inference finds that selChange is of type MatSelectChange
)
在这种情况下,类型推断工作正常。
我的问题是,如果我更改代码,如下面的代码片段,类型推断似乎不再工作
of(null)
.pipe(
switchMap(() => this.mySelect.selectionChange),
map(selChange => // here type inference does not work and selChange is of type {}
)
为什么这种不同的行为有任何建议?
selectionChange不是Observable类型。这是一个EventEmitter
SwitchMap返回Observable,因此您无法返回EventEmitter
如果要绑定数据,可以使用简单的输出:
<mat-select (selectionChange)="doSomething($event)" />
或者查看如何从EventEmitter创建一个Observable:
const obs$ = Observable.create(observer => {
emitter.on('message', val => observer.next(val));
emitter.on('error', err => observer.error(err));
});
(参考:RxJS - Create Observable from an EventEmitter's multiple events)