【问题标题】:How correctly implement this line inside Angular service?如何在 Angular 服务中正确实现这一行?
【发布时间】:2020-02-09 08:10:01
【问题描述】:

我找到了一个用于 Woocommerce 的 API 库并尝试将其集成到 Angular 中。

为了获取类别,看起来需要这一行。

const json = await WooWorker.getCategories();

我的服务如下所示:

 import { WooWorker } from "api-ecommerce";

  GetAllUsers(): Observable<any> {
    return this.http.get(`${BASEURL}/categories`);
  }

我需要替换这部分return this.http.get(${BASEURL}/categories); 使用此const json = await WooWorker.getCategories();,因为 API 使用第二种方式。用 observable 做这件事如何正确?

【问题讨论】:

标签: angular typescript rxjs angular6


【解决方案1】:
GetAllUsers(): Observable<any> {
   return WooWorker.getCategories();
  }

通过返回数据来尝试上述方法

【讨论】:

  • 感谢您的回复。它可以与github.com/inspireui/api-ecommerce/tree/master/src 这种API一起使用吗?我问它是因为提到了 API 反应原生,但文件看起来像简单的 JS 没有我们的反应导入。
  • 如果它返回 json 那么你需要通过调用你的观察者函数来获取 json
【解决方案2】:

你可以这样写。

import { WooWorker } from "api-ecommerce";
import { Observable, of } from 'rxjs';

async GetAllUsers(): Observable<any> {
  const json = await WooWorker.getCategories();
  return of(json);
}

of 是一个 RxJS 操作符,将输入转换为 observable。

【讨论】:

  • 感谢您的回复。它会和 github.com/inspireui/api-ecommerce/tree/master/src 这种 API 一起工作吗?我问它是因为提到了 API 反应本机,但文件看起来像简单的 JS 没有我们的反应导入。 ——
  • 应该可以。因为您必须通过 Angular 项目中的某个 NPM 包安装它。
  • 那么不调用Angular的http模块不会出问题?
  • 不,不会造成任何问题。先试试吧。
猜你喜欢
  • 2012-06-16
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 2015-06-25
  • 2015-11-25
  • 1970-01-01
  • 2018-04-17
相关资源
最近更新 更多