无法为模型订阅 forkjoin

Unable to subscribe a forkjoin to a model

我正在学习如何在 Angular 中使用 forkJoin;我可以使用回调(模型属性)发出单个请求并将其呈现在组件中,但是当涉及到这些组合请求时,不接受我在单个请求中使用的相同模型。它说 Type '[any, any]' is not assignable to type 'User'. 为什么?

模特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;

  }

}

服务:

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

forkJoin returns 数组中 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];
});