我正在使用 .share() 在服务的所有订阅者之间共享 Observable:
@Injectable()
export class ChannelsService {
private store: IChannel[] = [];
private _own: BehaviorSubject<IChannel[]> = new BehaviorSubject([]);
readonly own: Observable<IChannel[]> = this._own.asObservable().share();
...(the rest of the service basically makes CRUD http request and then calls this._own.next(result) to emit the result to all subscribers)
}
Run Code Online (Sandbox Code Playgroud)
问题:只有 Observable 的第一个订阅 (ChannelsService.own.subscribe(...)) 正在获取初始数据,其余订阅将“null”作为第一个订阅的值。接下来调用 this._own.next(result) 将正确地将其值发送给所有订阅者。
知道如何在多个订阅者之间 .share() 一个 Observable 并获取为所有订阅者发出的最后一个值吗?(我已经尝试过 .share().last() 但没办法...)。
谢谢!
我有一个BehaviorSubject被观察为消耗:
testForStack$: Observable<boolean>;
ngOnInit(){
const bs = new BehaviorSubject(true);
this.testForStack$ = bs
.asObservable()
.do(t => console.log('subscribed'))
.share();
}
Run Code Online (Sandbox Code Playgroud)
该可观察对象通过模板中的三个异步管道进行管道传输:
Sub1: {{testForStack$ | async}}<br>
Sub2: {{testForStack$ | async}}<br>
Sub3: {{testForStack$ | async}}
Run Code Online (Sandbox Code Playgroud)
问题是只有第一个(Sub1)获得true的值
Sub1: true
Sub2:
Sub3:
Run Code Online (Sandbox Code Playgroud)
如果删除.share(),则所有三个值都将获得true值,但这会导致多个订阅问题。
关于为什么使用BehaviorSubject导致此行为的任何想法?它被用作观察对象,因此我假设上面的代码可以正常工作。
这也与此答案类似: