我正在使用 .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() 但没办法...)。
谢谢!