javascript - 如何使用订阅 Observable 在 Angular 中执行查找
问题描述
首先,我是 Angular 的新手,所以我的方法可能不正确。请让我知道是否有更好的解决方案以及如何做到这一点。
我的目标是以表格格式(逐行)显示记录列表。我设法从数据库中检索记录列表,并且该列表仅包含外键 ID,这迫使我执行查找以便在 UI 渲染时显示名称。我不确定如何使用订阅来完成此操作。我什至不确定这是否是正确的方法,或者我必须将我的逻辑分解为多个动作。
我需要语法帮助,以便使用 Angular 订阅技术针对另一个数据源查找值以显示在表上。我包括我的表的输出、显示我的集合输出的调试会话和查找表值。
表单元素:
this.recoverySolutionForm = this.fb.group({
resourceDependencyId: [''],
rtoId: [''],
rtcId: { value: '', disabled: true },
rtGapId: [''],
rtActionId: [''],
strategyId: [''],
startImplementationId: [''],
rpoId: [''],
rpcId: { value: '', disabled: true },
rpGapId: [''],
rpActionId: [''],
comment: ['']
});
public getRecoverySolutions(deptId: string, bpId: string): void
{
this.recoverySolutions = null;
if (bpId)
{
console.log(`Selected Business Process Id: ${this._selectedBusinessProcessId}`);
// call service to retrieve recovery solutions from the database
this.recoveryySolutionService.getRecoverySolutions(deptId, bpId)
.subscribe(response =>
{
// response result
this.recoverySolutions = response;
// perform look up to map IDs into values
},
error => this.handleError(error));
}
}
// Data source for lookup tables
public getResourceDependencies(): void
{
this.service.getResourceDependencies()
.subscribe(response =>
{
this.resourceDependencies = response;
},
error => this.handleError(error),
() => console.log('Resource dependencies request completed')
);
}
public getRecoveryTimePeriods(): void
{
this.service.getRecoveryTimePeriods()
.subscribe(response =>
{
this.recoveryTimePeriod = response;
},
error => this.handleError(error),
() => console.log('Recovery time periods request completed ')
);
}
解决方案
我找到了我的答案。
我寻找一种更简洁的方式将 Id 映射到字符串(例如 X.id 到 X.name)。RxJS 运算符提供“combineLatest”。我通过 Deborah Kurata 的 PluralSight 视频(“RxJS in Angular: Reactive Development”)找到了答案。视频中的示例代码如下:
// Combine products with categories
// Map to the revised shape.
productsWithCategory$ = combineLatest([
this.products$,
this.productCategoryService.productCategories$
]).pipe(
map(([products, categories]) =>
products.map(product => ({
...product,
price: product.price * 1.5,
category: categories.find(c => product.categoryId === c.id).name,
searchKey: [product.productName]
}) as Product)
),
shareReplay(1)
);
推荐阅读
- javascript - Vue JS在组件中设置数据收集
- typescript - 在 Reactive forms angular 5 中使用 formarray 动态添加表单
- android - android 前台应用时每 5 秒更新一次状态
- spring-data-jpa - Spring with Querydsl:空指针异常
- sql - Sql 删除字符串中的子字符串(oracle 11g)
- compilation - 是否有工具可用于将 WebAssembly “组装”为 x86-64 本机代码?
- java - 解释用JAVA写的这一行
- r - grep multiple patterns Or condition on grouping data
- ios - How to set up UIScrollView programatically to scroll horizontally using autoLayout
- php - Laravel中效用函数的含义是什么