首页 > 解决方案 > Angular 8:在不订阅 observable 的情况下获取值

问题描述

以下是我需要在应用程序的各个部分订阅的两种方法:

  getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(this.url);
}

  getProductsByIds(ids: number[]): Observable<Products[]> {
    return this.getProducts()
      .map(products => products.filter(products => ids.includes(product.id)));
}

这适用于我的大多数组件,但在一个组件中,我id事先知道 -s 并且只想显示 id-s 1、2、9、18 的 4 个产品。我想像这样调用方法:) getProductsByIds([1, 2, 9, 18])。我只知道如何订阅这两个 observables,但我怎样才能一劳永逸地获得这 4 个产品(不需要值流)?我一定错过了一些基本的讲座..

标签: angularcomponentsobservable

解决方案


如果您只想获取一些值并将它们粘贴到没有 Observable 的变量中。从您的组件中,您可以像这样调用 getProductByIds :

service.getProductByIds([1,2,9.8]).take(1).subscribe(x => {
   this.variableWithProducts = x;
});

推荐阅读