angular - Angular 8 和在订阅中设置 observable
问题描述
在第一个组件中,我有一个变量this.products
,它是订阅 observable(s) 的结果。由于获取此变量的值涉及大量 swithcMap-ing 和类似的东西,我不想在第二个组件中重复所有复杂的逻辑,我也需要这个结果(不仅在 html 模板中)。是否可以为此目的执行以下操作?它工作正常,但我以前从未见过这样的模式,并且想知道它是否有问题。
a) 第一个组件
this.getProducts().lotsOfSwitchMapping
.subscribe((products) =>
{this.products = products;
this.setNiceItems.next(products)});
b) 第二部分
this.getNiceItems()
.subscribe(items => this.items = items);
所以this.items
和this.products
都是一样的。
解决方案
这完全没问题,并且是软件工程中的一种常见模式,简称为 DRY(不要重复自己)。为了更具体地了解 Angular,您绝对应该将您的逻辑外包到服务中,然后从您的组件中订阅服务中的 observable,这样您就有了一些模式,例如:
this.myItemsService
.itemsChanged() // where this returns the observable with all your switch mappings
.subscribe(items => this.items = items);
推荐阅读
- oracle - 使用 SQL Loader 解决“无效号码”错误
- jquery - Bootstrap 模态调用将不会运行,可能是构造函数问题
- javascript - 如何在 Java Script 中处理函数调用的异步性质
- chart.js - 将鼠标光标更改为图表js中的指针
- ms-access - 如何解决此代码中的运行时错误?
- angularjs - 如何在 ui-select 中设置默认值
- r - 在R中反向查找循环
- php - 自动填充 WooCommerce 优惠券中排除的产品
- python - 文本文件到字典,然后在 python 中打印信息
- php - Laravel dom 爬虫在 javascript 中搜索 img