Javascript 使用switchMap发出热布尔可观测值?
尝试创建一个isEmpty:ObservaleMethod,它使用开关映射发出一个热的ObservaleMethod。这就是我到目前为止所做的:Javascript 使用switchMap发出热布尔可观测值?,javascript,angular,typescript,rxjs,switchmap,Javascript,Angular,Typescript,Rxjs,Switchmap,尝试创建一个isEmpty:ObservaleMethod,它使用开关映射发出一个热的ObservaleMethod。这就是我到目前为止所做的: /** * Notifies observers when the store is empty. */ protected notifyOnEmpty = new ReplaySubject<E[]>(1); /** * Check whether the store is empty. *
/**
* Notifies observers when the store is empty.
*/
protected notifyOnEmpty = new ReplaySubject<E[]>(1);
/**
* Check whether the store is empty.
*
* @return A hot {@link Observable<boolean>} that indicates whether the store is empty.
*
* @example
<pre>
source.isEmpty();
</pre>
*/
isEmpty<E>():Observable<boolean> {
const isCurrentlyEmpty = values(this.entries).length == 0;
return this.notifyOnEmpty.pipe(startWith(isCurrentlyEmpty),
switchMap((entries:E[])=>entries.length == 0));
}
其思想是存储可以调用notifyOnEmpty.nextObject.valuesthis.entries,让订阅者知道存储是否为空
无论如何,switchMap语句会导致错误:
[ts]
“entries:E[]=>boolean”类型的参数不能分配给“value:E[],index:number=>observeInput”类型的参数。
类型“boolean”不可分配给类型“ObservableInput”。
参数项:E[]
想法?switchMap操作符用于在每个值上选择一个新的可观察值。您只需要一个常规映射,以便将每个数组映射到一个布尔值:
谢谢,这更有意义。我现在遇到另一个错误:[ts]类型为“OperatorFunction”的参数不能分配给类型为“OperatorFunction”的参数。类型“boolean | E[]”不能分配给类型“E[]”。类型“false”不可分配给类型“E[]”。有什么想法吗?是的,你会想做startwithvalues这个条目。这种方式映射总是映射E[]项。就目前的情况而言,您是从一个布尔值开始的,这就是为什么类型为boolean | E[]而不是E[]的原因。好吧!我最后用鼠标点击了startWith,因为在启动时,默认情况下条目的长度为零。再次感谢!切片存储现在具有可观察计数和空通知:
import { map, startWith } from 'rxjs/operators';
// ...
isEmpty<E>():Observable<boolean> {
return this.notifyOnEmpty.pipe(
startWith(values(this.entries)),
map((entries:E[]) => entries.length == 0)
);
}