gpt4 book ai didi

angular - 一种有条件地链接多个可观察对象的更简洁的方法

转载 作者:行者123 更新时间:2023-12-04 15:44:07 24 4
gpt4 key购买 nike

我有一种方法可以更新 MySQL 数据库上的“请求”。此请求可以选择包含附件,在这种情况下,我需要发出额外的 HTTP 请求来更新或添加附件记录(到不同的数据库表)并上传文件。

我有一个功能性方法来更新请求并可选择跳过附件 HTTP 请求,但我想知道一种更简洁的方法来实现这一点。总的来说,我是 Angular 和 RXJS 的新手,所以 rxjs 运算符的方法和使用可能不是最佳的。

基本上,我正在寻找在订阅之前有条件地链接一些可选的可观察对象的最佳方法,或者直接跳到订阅。

我正在寻找 iif 的潜在解决方案,返回 Observable.empty() 和不同的 rxjs 运算符,但当我只想完全跳过它们时,这些似乎是 map 函数中的选项。

onUpdateRequest() {
// if there are no attachments added to the request
if (this.attachments.length <= 0) {
this.callUpdateRequest().subscribe(() => {
// some page and form tidy up
});

// there are attachments, so process the new request and then file uploads
} else {
this.callUpdateRequest().pipe(
switchMap(() => {
return of(this.attachments);
}),
mergeMap(attachments => {
return attachments.map(attachment => {
return attachment;
});
}),
mergeMap(attachment => {
return this.attachmentsService.addAttachmentFile(attachment)
.pipe(map(fileData => {
return fileData;
}));
}),
mergeMap(fileData => {
return this.attachmentsService.addAttachment(
this.requestId, fileData.fileUrl
).pipe(
map(attachments => {
return attachments;
})
);
}),
takeLast(1)
)
.subscribe(() => {
// some page and form tidy up
});
)
}

private callUpdateRequest() {
return this.requestsService.updateRequest(
// all the request params
)
}

最佳答案

在 RxJs 中有一个有用的运算符(也是一个静态方法)iif()顾名思义,它的工作方式与 JS if/else 类似。

使用方式

iif(
() => state to check,
o1, // Observable to execute when statement is truthy
o2 // Observable to execute when statement is falsy
)

还有一个defer()您将需要按需创建可观察对象(否则 JS 将首先尝试编译可观察对象,这可能会导致一些错误,因此每次有可观察对象使用的传入值时我都会使用它)。

可以像这样使用

iif(
() => statmenet to check,
defer(() => o1),
defer(() => o2)
)

你的代码可能会被改写成下面的方式

getRequest(attachments) {
return iif(
() => attachments.length === 0,
defer(() => this.callUpdateRequest()),
defer(() => this.callUpdateRequest().pipe(
switchMapTo(of(attachments)),
mergeMap(attachments => {
return attachments.map(attachment => {
return attachment;
});
}),
mergeMap(attachment => {
return this.attachmentsService.addAttachmentFile(attachment)
.pipe(map(fileData => {
return fileData;
}));
}),
mergeMap(fileData => {
return this.attachmentsService.addAttachment(
this.requestId, fileData.fileUrl
).pipe(
map(attachments => {
return attachments;
})
);
}),
takeLast(1)
))
);
}

onUpdateRequest() {
this.getRequest(this.attachments).subscribe(() => {
// do whatever you want
})
}

我对您的代码进行了一些拆分,以使其更加通用和可测试。

附言为什么要写this.attachments.length <= 0可以低于 0 吗?

关于angular - 一种有条件地链接多个可观察对象的更简洁的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56610867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com