RxJS:forkJoin 延迟似乎不适用于超过 1 个调用
RxJS: forkJoin delay seems not working on more than 1 call
我有两个 http 调用,我需要延迟第二个调用或等待第一个调用完成,我添加了一个延迟,但第二个调用总是先执行。
ngOnInit
forkJoin({
getProductDetails: this.getProductDetails(),
getRelatedProducts: this.getRelatedProducts().pipe(delay(1000)) }).subscribe(res => {
this.productDetailsData = res.getProductDetails;
this.productsRelated = res.getRelatedProducts;
}, err =>{
// this.loader.hide();
});
}
获取产品详情
getProductDetails(): Observable < any > {
var queryString = `?productId=${this.productId}`;
return this.marketCommunication.productDetails(queryString)
.pipe(
map((res) => {
this.productCategoryId = res.productCategoryId
return res
}),
catchError((err) => {
throw err;
})
)
}
getRelatedProducts
getRelatedProducts(): Observable < any > {
console.log( this.productCategoryId) // -> returns null
var queryString = `?productCategoryId=${this.productCategoryId}&take=&skip=`;
return this.marketCommunication.publishedProductsByFilters(queryString)
.pipe(
map((res) => {
return res
}),
catchError((err) => {
throw err;
})
)
}
你需要改用switchMap来确保它们一个接一个地执行:
this.getProductDetails().pipe(
// now we have result of the first request and executing 2nd one.
switchMap(getProductDetails => this.getRelatedProducts().pipe(
// merging results together.
map(getRelatedProducts => ({
getProductDetails,
getRelatedProducts,
})),
)),
).subscribe(res => {
this.productDetailsData = res.getProductDetails;
this.productsRelated = res.getRelatedProducts;
});
我有两个 http 调用,我需要延迟第二个调用或等待第一个调用完成,我添加了一个延迟,但第二个调用总是先执行。
ngOnInit
forkJoin({
getProductDetails: this.getProductDetails(),
getRelatedProducts: this.getRelatedProducts().pipe(delay(1000)) }).subscribe(res => {
this.productDetailsData = res.getProductDetails;
this.productsRelated = res.getRelatedProducts;
}, err =>{
// this.loader.hide();
});
}
获取产品详情
getProductDetails(): Observable < any > {
var queryString = `?productId=${this.productId}`;
return this.marketCommunication.productDetails(queryString)
.pipe(
map((res) => {
this.productCategoryId = res.productCategoryId
return res
}),
catchError((err) => {
throw err;
})
)
}
getRelatedProducts
getRelatedProducts(): Observable < any > {
console.log( this.productCategoryId) // -> returns null
var queryString = `?productCategoryId=${this.productCategoryId}&take=&skip=`;
return this.marketCommunication.publishedProductsByFilters(queryString)
.pipe(
map((res) => {
return res
}),
catchError((err) => {
throw err;
})
)
}
你需要改用switchMap来确保它们一个接一个地执行:
this.getProductDetails().pipe(
// now we have result of the first request and executing 2nd one.
switchMap(getProductDetails => this.getRelatedProducts().pipe(
// merging results together.
map(getRelatedProducts => ({
getProductDetails,
getRelatedProducts,
})),
)),
).subscribe(res => {
this.productDetailsData = res.getProductDetails;
this.productsRelated = res.getRelatedProducts;
});