angular - 如何只订阅一次可观察的
问题描述
我正在尝试订阅两个 observable 并获取要存储在数组对象中的值。它工作正常,但我的问题是它重复了三次,我不明白。我在一项服务中这样做是为了创建一项新服务。下面是代码示例。我也想知道我可以使用 Promise 而不是 Angular 中的 observable 吗?或者我可以在获得价值后将 observable 转换为 promise 并解决?谢谢您的帮助
addEmployeeData() {
const employeeObservable = this.apiService.getEmployeeDataObservable();
employeeObservable.subscribe({
next: (res: any) => {
let employee = res;
const paramsObservable = this.apiService.getParamsObservable();
pageParamsObservable.subscribe({
next: (pageParams: any) => {
解决方案
是的,你可以像使用 Promises 一样使用 Observables:
async asyncAddEmployeeData(): Promise<any> {
return this.apiService.getEmployeeDataObservable()
.pipe(
mergeMap(employeeData => this.apiService.getParamsObservable()
.pipe(
tap((paramsData): void => {
// There is available data
// from apiService.getEmployeeDataObservable()
// as employeeData variable
// and data from apiService.getParamsObservable()
// as paramsData.
// You can do in tap function all the same
// as in next in the subscribe.
}),
)
),
)
.toPromise();
}
并像这里一样使用它:
async ngOnInit(): Promise<void> {
// ngOnInit just for example.
const someVariable = await this.asyncAddEmployeeData();
}
但是使用 Observable 的常规方式如下所示:
addEmployeeData(): Observable<any> {
return this.apiService.getEmployeeDataObservable()
.pipe(
mergeMap(employeeData => this.apiService.getParamsObservable()
.pipe(
tap(paramsData => {
// There is available data
// from apiService.getEmployeeDataObservable()
// as employeeData variable
// and data from apiService.getParamsObservable()
// as paramsData.
}),
)
),
take(1), // Just if you need only first value, if not, please, remove this string.
);
}
和订阅:
ngOnInit(): void {
// ngOnInit just for example.
this.subscription = this.addEmployeeData().subscribe();
}
不要忘记取消订阅以避免内存泄漏:
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
推荐阅读
- matlab - 在 Matlab 中使用平面切割裁剪 3D 网格
- oracle - HTTP500 错误 LoadRunner Oracle NCA 脚本
- c++ - 我可以制作一个基于子元素具有不同回报的虚函数吗?
- c++ - 找到一个非常大的数字的最右边的未设置位
- windows - 如何在 64 位 Windows 上准确修改本地描述符表?
- ios - Ionic ImagePicker - 应用程序在 IOS 12.3.1 上崩溃
- vb.net - 什么是 Visual Basic .Net 上的等效 hash_hmac PHP
- swift - 在 indexPath 处获取 UISwitch 状态到 UIcollectionView
- mysql - 将数据从一个表复制到另一个具有特定条件的表
- android - 带有 `?` 的可空 var 与 lateinit var