无法将forkjoin订阅到模型

时间:2018-01-18 18:42:25

标签: angular fork-join

我正在学习如何在Angular中使用forkJoins;我可以使用回调(模型属性)发出单个请求并在组件中呈现它,但是当涉及这些组合请求时,我不接受在单个请求中使用的相同模型。它说 Type'[any,any]'不能分配给'User'类型。为什么?

Model类:

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;

  }

}

服务:

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

1 个答案:

答案 0 :(得分:2)

forkJoin返回数组中api的结果。所以在你的代码中

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

values[resultsFromUsersApi, resultsFromPostsApi]

错误表明您正在尝试将数组分配给this.user,但用户被指定为类型用户

public user: User

如果您想在订阅中存储来自用户api的结果,您必须像

一样访问它
combined.subscribe(values => {
    this.user = values[0];
});