angular - 角度函数在 promise 中使用 then 和 return 语句
问题描述
我需要在我的函数中返回一个空字符串两次(请参阅 return ''。当我使用 catch 错误时,它正在工作,但我无法弄清楚如何编辑该函数,因此删除了 catch 错误。这是我的函数:
agencies$: Observable<Agency[]> = this.afs.collection<Agency[]>('agencies')
.valueChanges()
.pipe(tap(console.log),
mergeMap((agencies: Agency[]) => from(agencies)),
mergeMap((agency: Agency) => {
return forkJoin([
this.afStorage.storage
.refFromURL('gs://agency-logos-paid-keeper')
.child(`/thumbnails/${agency.agencyId}_700x100.png`)
.getDownloadURL().then(url => url).catch(error => {
return '';
}),
this.afStorage.storage
.refFromURL('gs://benefit-cards-paid-keeper').child(`/${agency.agencyId}_200x200.png`)
.getDownloadURL().then(url => url).catch(error => {
return '';
})])
.pipe(
tap(([logoUrl, benefitCardPhotoUrl]) => console.log('a', logoUrl, benefitCardPhotoUrl)),
map(([logoUrl, benefitCardPhotoUrl]) => ({
...agency, logoUrl, benefitCardPhotoUrl
})
), catchError((error) => {
return of({...agency});
}));
}),
map((agency: Agency) => [agency]),
scan((agencies: Agency[], agency: Agency[]) => {
const agencyExists = agencies.find(a => a.agencyId === agency[0].agencyId);
if (!agencyExists) {
return [...agencies, ...agency];
}
return agencies;
}));
之后我只想删除 .catch(error) (两者)。但是当我尝试它时,我得到了一个错误。如何删除 catch 错误,同时仍然有 return 语句。我知道这是一个基本问题,但我无法弄清楚。
解决方案
根据经验,混合 Promise 和 Observables 通常会导致问题。在您的代码中,我已将承诺更改为 Observables,并且一切似乎都有效
agencies$: Observable<any> = this.afs
.collection<Agency[]>("agencies")
.valueChanges()
.pipe(
tap(console.log),
mergeMap((agencies: Agency[]) => from(agencies)),
mergeMap((agency: Agency) => {
return forkJoin([
from(
this.afStorage.storage
.refFromURL("gs://agency-logos-paid-keeper")
.child(`/thumbnails/${agency.agencyId}_700x100.png`)
.getDownloadURL()
),
from(
this.afStorage.storage
.refFromURL("gs://benefit-cards-paid-keeper")
.child(`/${agency.agencyId}_200x200.png`)
.getDownloadURL()
)
]).pipe(
tap(([logoUrl, benefitCardPhotoUrl]) =>
console.log("a", logoUrl, benefitCardPhotoUrl)
),
map(([logoUrl, benefitCardPhotoUrl]) => ({
...agency,
logoUrl,
benefitCardPhotoUrl
}))
// catchError(error => {
// return of({ ...agency });
// })
);
}),
map((agency: Agency) => [agency]),
scan((agencies: Agency[], agency: Agency[]) => {
const agencyExists = agencies.find(
a => a.agencyId === agency[0].agencyId
);
if (!agencyExists) {
return [...agencies, ...agency];
}
return agencies;
})
);
请参阅此演示插图
推荐阅读
- python - 在 Thread 中使用 asyncio 的问题
- css - 在具有不同列大小的引导程序中包装网格
- jenkins - 声明式管道 - 运行 shell 命令
- c++ - 二进制表达式的无效操作数('std::ostream'(又名'basic_ostream
') 和 'sound_ctl') - c# - Unity Coroutine Yield 似乎每次都关闭协程
- python - 使用矢量化在 nan 之后在 numpy 数组的行中获取第一个/第二个/第三个...值
- c++ - 给植物浇水(竞争性编程)
- java - 无法解析方法“createDirectStream”Java Spark Kafka
- php - 应用程序在网络服务器上完全失败,而在 localhost 上运行良好
- php - PHP Trait 函数与另一个 trait 函数冲突