首页 > 解决方案 > 如何在 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我怎样才能捕获所有的数组元素?

标签: arraysangulartypescriptrxjs

解决方案


您没有在 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
])

推荐阅读