Mellville
Mellville

Reputation: 1097

Unable to subscribe a forkjoin to a model

I'm learning how to work with forkJoins in Angular; I can make a single request with a callback (model attribution) and render it in the component, but when it comes to these combined requests, the same model I use in the single request isn't accepted. It says Type '[any, any]' is not assignable to type 'User'. Why?

The Model class:

export class User {


  public name: string;
  public email: string;
  public phone: string;
  public body: string;

  constructor(user: any) {

    this.name = user.name;
    this.email = user.email;
    this.phone = user.phone;
    this.body = user.body;

  }

}

The service:

export class DataService {

  public user: User;
  public url = 'https://jsonplaceholder.typicode.com/users/';

  constructor(private http: Http) {   }


  getFork(callback: (receiver: User) => void) {

  const combined = Observable.forkJoin(
    this.http.get('https://jsonplaceholder.typicode.com/users/').map(res => res.json()),
    this.http.get('https://jsonplaceholder.typicode.com/posts/').map(res => res.json())
  );

  combined.subscribe(values => {
    this.user = values; -> 'this.user' gets red
    callback(this.user);
    console.log(this.user);
  });
 }


// This method works fine
  getData(callback: (receiver: User) => void) {

    return this.http.get(this.url)
      .map(res => res.json())
      .subscribe(users => {
        this.user = users;
        callback(this.user);
        console.log(this.user);
      });
  }

Upvotes: 0

Views: 254

Answers (1)

LLai
LLai

Reputation: 13406

forkJoin returns the results of the apis in an array. So in your code

combined.subscribe(values => {
    this.user = values; -> 'this.user' gets red
});

values is [resultsFromUsersApi, resultsFromPostsApi]

The error is stating that you are trying to assign an array to this.user, but user is specified as type User

public user: User

If you want to store the result from the users api in your subscribe you have to access it like

combined.subscribe(values => {
    this.user = values[0];
});

Upvotes: 2

Related Questions