angular - 如何只获取传入的 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(...)因为我的怀疑告诉我它有一些东西。不过,我没有让它发挥作用,并且失去了信心,因为我什至不确定这是可行的方法。
解决方案
另一种选择是从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;
}
推荐阅读
- google-apps-script - 如何将 Google Apps 脚本项目 ID 链接/绑定到 Google 电子表格
- c++ - 如何让QTableView在没有聚焦的情况下自动更新内容?
- php - 如何使用 pusher 的 + laravel 的私人频道隐藏错误 403(但它有效)?
- python - 由于路径中有空格,无法在 gitbash 中运行 dbt
- typescript - 如何将对象中的每种类型的属性映射到接口中的属性?
- javascript - 在 Javasript 中复制 MySQL 数组格式
- python - Python Pandas 递归地划分列
- postgresql - 您可以使用patronictl 更改pg_hba.conf 吗?
- node.js - 在 Node JS 上使用 RFID 阅读器
- python - 从 Python 调用 C 函数会传递不正确的字符串