如何在Angular中使用forkJoin()处理返回的数组?

时间:2019-10-11 08:56:10

标签: arrays angular typescript rxjs

我正在使用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的结果,又如何捕获所有数组元素呢?

1 个答案:

答案 0 :(得分:1)

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