RxJS Observable用新数据替换流
我有一个服务,它在初始化时更新可观察对象的数据,然后在http搜索时更新 使用next将记录添加到observable中的数组中,但是如何用新的集合替换这些记录呢 search.service.tsRxJS Observable用新数据替换流,rxjs,Rxjs,我有一个服务,它在初始化时更新可观察对象的数据,然后在http搜索时更新 使用next将记录添加到observable中的数组中,但是如何用新的集合替换这些记录呢 search.service.ts private searchSource = new BehaviorSubject<any>(this.getInitialCollections()); public currentState = this.searchSource.asObservable();
private searchSource = new BehaviorSubject<any>(this.getInitialCollections());
public currentState = this.searchSource.asObservable();
public getInitialCollections() {
return this.apiService.post(this.searchApi)
.subscribe(data => this.changeSubject(data));
}
public search(phrase: string) {
return this.apiService.post(this.searchApi, { phrase: phrase })
.subscribe(data => this.changeSubject(data));
}
private changeSubject(results: object) {
this.readCollectionResult(results).map(data => this.searchSource.next(data));
}
private readCollectionResult(result: any): Asset[] {
return (result && result.data) ? result.data.map(asset => asset) : [];
}
组件技术
export class SearchDataSet {
/** Stream that emits whenever the data has been modified. */
dataChange: BehaviorSubject<Asset[]> = new BehaviorSubject<Asset[]>([]);
get data(): Asset[] { return this.dataChange.value; }
constructor(
private _searchService: SearchService
) {
this.initialize();
}
records = this.data.slice();
initialize() {
this._searchService.currentState
.subscribe(item => !item.id ? null : this.addRecord(item));
}
/** Adds a new asset to the database. */
addRecord(item: object) {
this.records.push(item);
this.dataChange.next(this.records);
}
}
'使用下一步将记录添加到可观察对象中的数组'
实际上,由于searchSource是一个BehaviorSubject,它只能保存一个值,因此searchSource.nextdata将用数据替换searchSource的当前内容
您可能需要一个附加的方法
私有addToSubjectresults:对象{
this.searchSource.subscribebecurrent=>{
const assets=this.readCollectionResultresults;
this.searchSource.nextcurrent.concatassets;
};
}
我看到项目被添加到从observable返回的结果数组中的行为-当我调用我的搜索函数时,结果只是那些附加到currentState observable末尾的项目rry,我有一个关于readCollectionResult的注释,然后意识到你已经发布了它,所以改变了答案。你真的可以在下一个函数中这样做current.pushassets吗?我试试看我能不能做个测试。你确定searchSource的当前值正在被修改,你不只是看到下一个发出的值吗?是的,这太奇怪了,我将发布使用该服务的组件