RXJS 和 Nestjs 返回值的问题
我从端点获取一些 JSON(为此我使用 @nestjs/axios
)。问题在于响应是一个 Observable。返回值时这会使事情变得复杂。我似乎无法让 async/await 工作,我真的没有主意了...
这是我的终点:
async getBalance({ address, network }: WalletDto): Promise<any> {
let nativeBalance: string
try {
this.httpService
.get<{ balance: string }>(
`https://deep-index.moralis.io/api/v2/${address}/balance?chain=${network}`,
{
headers: {
Accept: 'application/json',
'X-Api-Key': 'lol',
},
},
)
.subscribe({
next: ({ data }) => {
nativeBalance = utils.formatEther(data.balance)
},
complete: () => {
const chain = supportedChains.find(
({ name }) => name.toLowerCase() === network,
)
return {
chain,
nativeBalance,
}
},
})
} catch (error) {
// TODO handle error
}
}
我已经搞乱了 .pipe()
但不明白什么它的作用或工作原理...顺便说一句,supportedChains 是一个静态数组,不是获取的一部分。
I'm getting some JSON from an endpoint (I'm using @nestjs/axios
for this). The issue is that the response is an Observable
. This complicates things when returning values. I can't seem to get async/await to work, I'm truly out of ideas...
Here's my endpoint:
async getBalance({ address, network }: WalletDto): Promise<any> {
let nativeBalance: string
try {
this.httpService
.get<{ balance: string }>(
`https://deep-index.moralis.io/api/v2/${address}/balance?chain=${network}`,
{
headers: {
Accept: 'application/json',
'X-Api-Key': 'lol',
},
},
)
.subscribe({
next: ({ data }) => {
nativeBalance = utils.formatEther(data.balance)
},
complete: () => {
const chain = supportedChains.find(
({ name }) => name.toLowerCase() === network,
)
return {
chain,
nativeBalance,
}
},
})
} catch (error) {
// TODO handle error
}
}
I've messed around with .pipe()
but don't understand what it does or how it works... Btw, supportedChains
is a static array, not part of the fetch.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为可观察对象的超级简短介绍:如果 Promise 是一个仅代表一个最终值的对象,那么可观察对象就是一个代表任意数量最终值流的对象。 Observables 附带了一组用于操作值流的运算符函数(您提到的管道函数用于传递您想要应用的任何运算符)。
如果您只想从可观察量转换为承诺,那么您可以使用可观察量的
.toPromise
属性来实现。如果您使用的是 rxjs 版本 7,则toPromise
已弃用,您可以使用firstValueFrom
或lastValueFrom
。As a super brief intro to observables: if a Promise is an object that represents exactly one eventual value, then an Observable is an object that represents a stream of any number of eventual values. Observables come with a collection of operator functions for manipulating the stream of values (that pipe function you mentioned is used to pass in any operators you want to apply).
If you just want to convert from observables to promises, then you can do so with the
.toPromise
property on observables. If you're using rxjs version 7 thentoPromise
is deprecated and instead you can usefirstValueFrom
orlastValueFrom
.