首页 > 解决方案 > 如何只获取传入的 observable 中的一个字段?

问题描述

我有一个可观察的,我使用如下。

...
const id = 1337;
this.service.getThing(id).subscribe(
  suc => doSomething(suc.name),
  err = doSomethingElse()
);

自从我开始使用异步管道以来,我的大部分 observables 都是这样进行的。

thing$: Observable<Thing>;
...
ngOnInit(){
  this.thing$ = this.service.getThing(1337);
}

我可以在 HTML 中使用结果,如下所示,但我很好奇是否可以声明一个操作,当实现时,从 observable 获取值并且只选择某个字段。

<div *ngIf="thing$ | async as thing>
  {{thing.name}}
</div>

我只想访问名称,而不必将其从事物中提取出来。

我试过玩pipe(...)因为我的怀疑告诉我它有一些东西。不过,我没有让它发挥作用,并且失去了信心,因为我什至不确定这是可行的方法。

标签: angulartypescriptasynchronousobservable

解决方案


另一种选择是从rxjs库中提取。

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ProductService } from '../shared/product.service';
import { pluck } from 'rxjs/operators';

@Component({
    selector: 'app-product',
    template: `<div *ngIf="productName$ | async as productName">
          {{productName}}
        </div>`,
    styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
    productName$: Observable<string>;

    constructor(private productService: ProductService) { }

    ngOnInit() {
        this.productName$ = this.productService.getProduct(1).pipe(pluck('productName'));
    }

}

此示例从产品服务返回的产品中提取产品名称。

export interface Product {
    id: number;
    productCode: string;
    productName: string;
}

推荐阅读