arrays - 如何在 Angular 中使用 forkJoin() 处理返回数组?
问题描述
我正在使用forkJoin()
以下代码处理多个可观察对象:
forkJoin([
this.userRoleService.getAll(), // result is an array of UserRole models
this.userService.getOne(id), // result is a single User model
this.countyService.all(), // result is an array of County models
]).subscribe(([userRoles, userModel, counties]) => {
console.log(userRoles, userModel, counties);
// handle the result
});
正如您在结果中看到的,我需要获取两个数组和一个对象。但在这种情况下,我在控制台中得到了这个:
(2) [UserRole, UserRole]
UserModel {api_endpoint: "user/", role: UserRole, id: 1, name: "admin", email: "admin@admin.test", …}
CountyModel {id: 20, name: "Hazard"}
在这里,我得到了一个带有两个UserRole
实例的数组,一个UserModel
实例和一个CountyModel
实例。
这是county.service.ts
:
import { Injectable } from '@angular/core';
import { CountyModel } from 'src/app/models/County.model';
@Injectable({
providedIn: 'root'
})
export class CountyService {
db: CountyModel[] = [];
constructor() {
const items = JSON.parse( localStorage.getItem('counties'));
items.forEach( (item: any) => {
this.db.push(new CountyModel().init(item));
});
}
all(): CountyModel[] {
return this.db ? this.db : [];
}
}
因此,服务的all()
方法在每种情况下都返回一个数组。但是为什么我只得到这个数组的最后一个元素作为结果,forkJoin
我怎样才能捕获所有的数组元素?
解决方案
您没有在 CountyService 中返回可观察的数组,请尝试使用of()
forkJoin([
this.userRoleService.getAll(), // result is an array of UserRole models
this.userService.getOne(id), // result is a single User model
of(this.countyService.all()), // result is an array of County models
])
推荐阅读
- sas - 如何在 SAS 中找到每个按组的观察之间的持续时间?
- amazon-web-services - AWS lambda 函数在通过 POST 发送文件时返回 HTTP 403
- javascript - 与后端方法交换 HTML 内容后,如何激活脚本文件?
- azure-devops - 仅当 Azure Pipelines 中的指定文件夹没有更改时触发构建
- android - 我可以在主线程中同时运行两个进程吗
- java - 无法解析方法“订阅(io.reactivex.scheduler)”
- mongodb - 通过 kubectl run 在单个 pod 中运行两个容器不会终止具有两个容器的 pod
- vb.net - 石头剪刀布游戏画框不换
- oracle - 从 Oracle DB 加载数据时,列值作为子字符串出现
- java - 类中的Java android房间列表无法弄清楚如何将此字段保存到数据库中