RxJS Observable用新数据替换流

时间:2017-11-06 21:23:16

标签: rxjs

我有一项服务,在初始化时更新可观察的数据,然后在http搜索时更新。

使用next()将记录添加到observable中的数组中,但是如何用新的set替换这些记录呢?

search.service.ts

 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) : [];
    }

component.ts

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);
    }
}

1 个答案:

答案 0 :(得分:1)

  

'使用next()将记录添加到可观察的'

中的数组中

实际上,由于searchSource是一个BehaviorSubject,它只能保存一个值,因此searchSource.next(data) 将searchSource的当前内容替换为 数据。

您可能需要其他方法

private addToSubject(results: object) {
  this.searchSource.subscribe(current => {
    const assets = this.readCollectionResult(results);
    this.searchSource.next(current.concat(assets));
  });
}