如何在获取 HTTP 请求结果时强制转换对象

How can I force casting object when getting result of HTTP Request

我正在向响应的外部 API 发出 HTTP 请求:

{
id: 1,
user_id: 1,
name: "Fake Tournoi",
slug: "fake-tournoi",
dateIni: "2018-06-13 00:00:00",
dateFin: "2018-06-14 00:00:00",
registerDateLimit: "2018-06-10 00:00:00",
sport: 1,
promoter: "promoter2",
host_organization: "host2",
technical_assistance: "tech2",
rule_id: 1,
type: 0,
venue_id: 1,
level_id: 7,
created_at: "2018-06-02 18:56:44",
updated_at: "2018-06-12 10:55:46",
deleted_at: null,
championships: [
  {...},
  {...},
  {...},
  {...}
  ]
}

所以,这里的主要对象是 Tournament,然后锦标赛是 Championship 个对象的数组

我以为我在获取数据时正在转换对象:

getTournamentWithTrees(): Tournament {
    this.loading = true;
    this.treeService.getTournamentWithTrees(this.slug)
      .pipe(first())
      .subscribe(tournament => {
        this.tournament = tournament;
        this.loading = false;
      }, err => {
        this.loading = false;
      });
    return null;
  }

这个方法应该有一个Tournament类型,然后在Tournament定义中,我有:

export class Tournament {
  id: number;
  ...
  competitors: Competitor[];
}

事情是当我尝试在 Tournament 对象或 Championship 对象上使用方法时:

<div *ngIf="championship.hasPreliminary()">
    has Prelim
</div>

我收到一个错误:

ERROR TypeError: _v.parent.context.$implicit.hasPreliminary is not a function

我猜是因为我的冠军数据不算冠军 目的。我应该怎么做才能解决这个问题?

使用这样的构造函数:

export class Tournament {
  constructor(payload: Object) {
    Object.assign(this, payload);
  }
}

并这样称呼它:

this.http.get('...')
  .map(tournaments => tournaments
    .map(tournament => new Tournament(tournament))
  );

当您发出 HTTP 请求时,不会键入您的有效负载:为您的 HTTP 调用提供 class 只会启用您的 IDE 的自动完成。