如果返回的结果为空,则RxJS SwitchMap不会完成

时间:2018-01-05 21:02:06

标签: typescript rxjs observable

我有一个显示加载微调器的数据表。当this.rendering设置为true时,加载程序会显示 - 如果从this._CollectionDataSet.results返回的结果是一个空数组,则序列卡在switchMap上并且没有完成 - 为什么会这样?

enter image description here

datasource.ts

connect(): Observable<Collection[]> {
    // Listen for any changes in the base data, sorting, filtering, or pagination
    const displayDataChanges = [
        this._CollectionDataSet.dataChange,
        this._sort.sortChange
    ];

    return Observable.merge(...displayDataChanges)
        .startWith(null)
        .switchMap(() => {
            this.rendering = true;
            return this._CollectionDataSet.dataChange;
        })
        .catch(() => {
            return Observable.of(null);
        })
        .map((result) => {
            this.rendering = false;
            return result;
        })
        .map(result => {
            if (!result) { return []; }

            this._recordsTotal = result.length;

            const sortedData = this.sortData(result.slice());

            this.renderedData = sortedData;

            return this.renderedData;
        });
}

dataset.ts

dataChange: BehaviorSubject<Collection[]> = new BehaviorSubject<Collection[]>([]);
get results(): Collection[] { return this.dataChange.value; }

constructor(
    private _collectionService: CollectionService,
    private route: ActivatedRoute,
    private router: Router
) {
    this.route.params.subscribe((param: any) => {
        this._collectionService.view(param.id).subscribe((results) => this.update(results));
    });
}

update(results: Collection[]) {
    results && this.dataChange.next(results);
}

1 个答案:

答案 0 :(得分:1)

您没有向我们展示{{ brackets }}是如何定义的,而是基于您提供的签名

_CollectionDataSet.results

我认为(): Collection[] 的类型为results。这里的问题是Collection[]必须返回 Observable 。如果您已经拥有要映射到的数据,则无需观察,您只需使用switchMap即可。

此外,使用map时,应使用副作用运算符(dotap运行副作用。这会将您的代码减少到

pipe

虽然这些副作用可能相当无用。如果.do(() => this.rendering = true) .map((): Collection[] => this._CollectionDataSet.results) .catch(result => Observable.of(null)) .do(() => this.rendering = false) 确实只是一个数组,那么所有这些都会瞬间发生,你也可能不会为此显示一个微调器。