你如何声明一个带参数的 GET 调用? [英] How do you declare a GET call with parameters?

查看:41
本文介绍了你如何声明一个带参数的 GET 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 API 获取数据的一种技术是在服务中像这样声明它:

A technique of getting data from a an API is to declare it like this in the service:

getItems$ = this.httpClient.get<Item[]>(this.url);

然后订阅它或在消费组件中使用异步.

then either subscribe to it or utilize async in the consuming component.

如果 get 调用需要像 get by id 这样的参数,你会怎么做?

How would you do this if the get call requires parameters like get by id?

以上是使用 RxJS 流的声明性方法的示例.getItems$ 是一个属性.

The above is an example of a declarative approach to working with RxJS streams. The getItems$ is a property.

所以问题是,当使用带有 property 定义流的声明式方法而不是调用 getItems(itemId) 方法时,如何传入参数?

So the question is, when using a declarative approach with a property defining the stream instead of calling a getItems(itemId) method, how to you pass in parameters?

推荐答案

要处理任何参数",您可以使用 Subject 或 BehaviorSubject 创建另一个动作流.参数"然后被发射到流中.

To handle any "parameters", you create another action stream using Subject or BehaviorSubject. The "parameter" is then emitted into the stream.

这是我的一个应用程序中的一个示例.

Here is an example from one of my applications.

  // Handle product selection action
  private productSelectedSubject = new BehaviorSubject<number>(0);
  productSelectedAction$ = this.productSelectedSubject.asObservable();

  product$ = this.productSelectedAction$
    .pipe(
      filter(id => !!id),
      switchMap(selectedProductId =>
        this.http.get<Product>(`${this.productsUrl}/${selectedProductId}`)
      ));

  // Selected product was changed
  changeSelectedProduct(selectedProductId: number): void {
    this.productSelectedSubject.next(selectedProductId);
  }

这里我们创建了一个初始值为 0 的 BehaviorSubject.(您可以改为使用没有初始值的 Subject.)

Here we create a BehaviorSubject with an initial value of 0. (You could instead use a Subject with no initial value.)

当用户选择一个产品(或者确定了具体的产品)时,该产品的 id 被发送到 productSelectedSubject

When the user picks a product (or however the specific product is determined) the id of that product is emitted into the productSelectedSubject

此代码然后使用管道在每次有新产品 Id 发送到流中时做出反应.管道中的第一个运算符过滤掉任何无效的 ID.然后 switchMap 使用发出的产品 ID 来发出 http get.

This code then uses a pipeline to react every time there is a new product Id emitted into the stream. The first operator in the pipeline filters out any invalid Ids. The switchMap then uses the emitted product Id to issue the http get.

我有一个完整的例子,它也设置了额外的参数".在此处进行分页:https://github.com/DeborahK/Angular-ActionStreams

I have a complete example of this that also sets up additional "parameters" for pagination here: https://github.com/DeborahK/Angular-ActionStreams

这篇关于你如何声明一个带参数的 GET 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆