如何以正确的方式使用可观察到的物品正确使用Nestjs/Axios从远程URI加载数据?

发布于 2025-01-20 17:00:17 字数 1585 浏览 1 评论 0原文

NestJs 建议使用从 @nestjs/axios 导入的 HttpModule 来执行对外部 API 的请求。我知道 HttpService 将响应转换为可观察对象。但是,这使得在想要从远程服务获取数据并立即使用这些数据的服务内部获取数据变得困难:

try {
  const metaData = await this.httpService.get(tokenUri).pipe(
    map((res) => res.data),
    catchError((e) => {
      throw new HttpException(e.statusText, e.status);
    }),
  );
  console.log("---------------")
  console.log(metaData);
  console.log("---------------")
} catch (e) {
  this.logger.error(`Unable to fetch MetaData from ${tokenUri}. ` + e.toString());
}

我得到的是这样的:

---------------
Observable {
  source: Observable {
    source: Observable { _subscribe: [Function (anonymous)] },
    operator: [Function (anonymous)]
  },
  operator: [Function (anonymous)]
}
---------------

我不想使用 subscribe< 的原因/code> 直接在 get 执行之后,这样我就无法捕获 404 错误。在互联网上,我找到了 pipecatchError 的组合来做到这一点。这样我就能够再次捕获错误,但我不再获得任何数据。

因此,我仍然需要执行 subscribe 来订阅我的数据。 所以我想出了这个:

this.logger.debug('Found Token-URI: ' + tokenUri);
try {
  const metaData = await this.httpService.get(tokenUri).pipe(
    map((res) => res.data),
    catchError((e) => {
      throw new HttpException(e.statusText, e.status);
    }),
  );

  metaData.subscribe((x) => {
    // here is my data:
    console.log(x);
  });
} catch (e) {
  this.logger.error(`Unable to fetch MetaData from ${tokenUri}. ` + e.toString());
}

这种方式可行,但我不确定从 nextjs/axios 开发人员的角度来看这是否是正确的方式。

NestJs suggests to use the HttpModule imported from @nestjs/axios to perform requests to external APIs. I understand that the HttpService transforms the responses into Observables. However, it makes it hard to fetch data inside of my service that wants to fetch data from a remote service and immediately work with these data:

try {
  const metaData = await this.httpService.get(tokenUri).pipe(
    map((res) => res.data),
    catchError((e) => {
      throw new HttpException(e.statusText, e.status);
    }),
  );
  console.log("---------------")
  console.log(metaData);
  console.log("---------------")
} catch (e) {
  this.logger.error(`Unable to fetch MetaData from ${tokenUri}. ` + e.toString());
}

What I get is this:

---------------
Observable {
  source: Observable {
    source: Observable { _subscribe: [Function (anonymous)] },
    operator: [Function (anonymous)]
  },
  operator: [Function (anonymous)]
}
---------------

The reason why I don't want to use subscribe directly after the execution of get is that this way I was not able to catch 404 errors. On the internet I found the combination of pipe and catchError in order to do so. This way I am able again to catch the errors but I don't get any data anymore.

Thus, I have still to execute subscribe to subscribe on my data.
So I came up with this:

this.logger.debug('Found Token-URI: ' + tokenUri);
try {
  const metaData = await this.httpService.get(tokenUri).pipe(
    map((res) => res.data),
    catchError((e) => {
      throw new HttpException(e.statusText, e.status);
    }),
  );

  metaData.subscribe((x) => {
    // here is my data:
    console.log(x);
  });
} catch (e) {
  this.logger.error(`Unable to fetch MetaData from ${tokenUri}. ` + e.toString());
}

This way it works, but I am not sure if it is the right way from the nextjs/axios developers point of view.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

给我一枪 2025-01-27 17:00:17

我认为在这种情况下,您可以使用错误处理程序来简化您的代码,该错误处理程序可以提供给.subscribe函数。因此,您不必使用尝试/捕获并重新纠正错误,而可以简单地做:

this.logger.debug('Found Token-URI: ' + tokenUri);

const metaData$ = this.httpService.get(tokenUri).pipe(map((res) => res.data));

metaData$.subscribe(
   (x) => console.log(x),
   (err) =>  this.logger.error(`Unable to fetch MetaData from ${tokenUri}. ` + e.toString())
);

作为旁注,我建议阅读此博客 - post 关于RXJS错误处理。

I think in this case you can simplify your code by using an error-handler that you can provide to the .subscribe function. So instead of having to use try/catch and rethrowing the error, you could simply do:

this.logger.debug('Found Token-URI: ' + tokenUri);

const metaData$ = this.httpService.get(tokenUri).pipe(map((res) => res.data));

metaData$.subscribe(
   (x) => console.log(x),
   (err) =>  this.logger.error(`Unable to fetch MetaData from ${tokenUri}. ` + e.toString())
);

As a side note, I'd recommend reading this blog-post regarding rxjs error-handling.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文