【发布时间】:2020-02-03 19:23:13
【问题描述】:
在 RxJS (ES6) 中,我试图在单个 Observable 中通过一系列顺序操作获得结果。
我不确定我是否必须使用 forkJoin(但我希望操作按顺序执行)或 concat 运算符(但我希望在所有操作都执行时在最后收到通知) .
我试过了:
forkJoin
sync(): Observable<any> {
return from(this.db.getProducts()).pipe(
map(products => {
if ( !products ) {
return of(true);
}
const batch: Observable<any>[] = [];
for ( const product of products ) {
if ( product.toBeSync ) {
batch.push(this.api.updateProduct(product));
}
}
return forkJoin(batch);
})
);
}
连接
sync(): Observable<any> {
return from(this.db.getProducts()).pipe(
map(products => {
if ( !products ) {
return of(true);
}
const batch: Observable<any>[] = [];
for ( const product of products ) {
if ( product.toBeSync ) {
batch.push(this.api.updateProduct(product));
}
}
return concat(batch);
})
);
}
在这两种情况下,我都看不到来自 HttpClient 的可观察对象正在执行他们的工作(没有发送 http 请求),但我可以看到日志记录。
批处理中被调用的方法如下:
updateProduct(product: Product) {
console.log('calling...');
const options = this.getDefaultRequestOptions();
return this.http.post('update_product', product, options);
}
我像下面这样调用sync()函数:
this.productService.sync().subscribe(() => {
console.log('sync done');
}, error => this.utils.handleError(error));
输出:
(8) calling...
sync done
但没有启动 HTTP 请求。
如果我在管道图中的 forkJoin/concat 之外执行相同操作,我可以看到发送的 HTTP 请求。
sync(): Observable<any> {
const product = new Product(null, 'Title', 'Desc.', 'CODE');
return this.api.updateProduct(product);
}
我错过了什么?
--- 更新 - 解决方案 ---
sync(): Observable<any> {
return from(this.db.getProducts()).pipe(
flatMap(products => {
if ( !products ) {
return of(true);
}
const batch: Observable<any>[] = [];
for ( const product of products ) {
if ( product.toBeSync ) {
batch.push(this.api.updateProduct(product));
}
}
console.log(batch);
return concat(...batch);
// return forkJoin(batch);
})
);
【问题讨论】:
标签: typescript rxjs concat angular-httpclient fork-join