startWith()返回主题
问题描述:
我想使用默认值的主题发出值。startWith()返回主题
startWith("def")
是此方法。
subject = new Rx.Subject().startWith("def value");
不幸startWIth
回报Observable
,所以我不能使用onNext()
,这是我使用的首位主题的唯一原因。这个问题的解决方法是什么?
subject.onNext("next val"); //cannot call onNext, it is not a function of Observable
答
只是跟踪可观察的和主题。我通常做类似...
export class FooService {
private _foos: Subject<Foo> = new subject<Foo>();
public get foos: Observable<Foo> {
return this._foos.startsWith(...);
}
public emitFoo(foo: Foo) {
this._foos.next(foo);
}
}
答
你的问题并不完全清楚。如果你希望所有观察者在其他任何事情之前看到“def value”,那么使用@Pace的答案。
但是如果你想所有观察员开始以“最近发出的价值”,你发出的第一个值之前使用“Def值”,如果他们订阅,然后用BehaviorSubject
:
var subject = new BehaviorSubject("default val");
subject.subscribe(...); // sees "default val", then anything you emit.
subject.next("foo");
subject.subscribe(...); // sees "foo", then anything else you emit (does not see "default val")