0

I'm using forkJoin() to handle multiple observables with this code:

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
});

As you see in results I need to get two arrays and a single object. But in this scenario I get this in the console:

(2) [UserRole, UserRole]
UserModel {api_endpoint: "user/", role: UserRole, id: 1, name: "admin", email: "[email protected]", …} 
CountyModel {id: 20, name: "Hazard"}

Here I got one array with two of UserRole instances, one UserModel instance and one CountyModel instance.

Here is the 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 : [];
  }
}

So the service's all() method return with an array in every case. But why I get only the last element of this array as result in the forkJoin and how can I catch all of the array elements?

1
  • If this is real code, the forkJoin will never complete, because the getAll method returns an array, not observable. Commented Oct 11, 2019 at 9:09

1 Answer 1

1

You are not returning observable of array in countyService, try wrap it with 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
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.