Angular 模板中被视为字符串的日期对象

Angular 模板中被视为字符串的日期对象,angular,angular2-template,Angular,Angular2 Template,我正在尝试使用Angular2日期管道来格式化日期。我将该类作为对象的模型: export class Match { Id: number; MatchDate: Date; constructor( id: number, matchDate: Date ) { this.Id = id; this.MatchDate = matchDate; } } 我将匹配对象提取到我的组件: impo

我正在尝试使用Angular2日期管道来格式化日期。我将该类作为对象的模型:

export class Match {
    Id: number;
    MatchDate: Date;

    constructor(
        id: number,
        matchDate: Date
) {
        this.Id = id;
        this.MatchDate = matchDate;
    }
} 
我将匹配对象提取到我的组件:

import {Component, OnInit} from 'angular2/core';
import {Match} from '../core/models/match';
import {MatchService} from '../core/services/match.service';

@Component({
    selector: 'home',
    templateUrl: './app/components/home.html',
    directives: [],
    providers:[MatchService]
})

export class Home implements OnInit {
    nextMatch: Match;
    lastMatch: Match;
    errorMessage: string;


    constructor(
        private _matchService: MatchService
    ) { }

    getNextMatch() {
        this._matchService.getNextMatch()
            .subscribe(
            nextMatch => this.nextMatch = nextMatch,
            error => this.errorMessage = <any>error
            );
    }

    getLastMatch() {
        this._matchService.getLastMatch()
            .subscribe(
            lastMatch => this.lastMatch = lastMatch,
            error => this.errorMessage = <any>error
            );
    }

    ngOnInit() {
        this.getNextMatch();
        this.getLastMatch();
    }
}

我认为你的服务没有返回日期。如果从HTTP请求中获取日期,则不会从响应中获取日期,因为JSON格式不支持日期

有关更多详细信息,请参见此问题:


    • 我认为您的服务没有返回日期。如果从HTTP请求中获取日期,则不会从响应中获取日期,因为JSON格式不支持日期

      有关更多详细信息,请参见此问题:


      您的
      匹配服务如何检索日期?如果它来自HTTP请求,您是否将它们转换为日期?您的MatchService需要返回JavaScript日期对象。我假设它正在返回字符串。我已经从我的MatchService添加了代码。我认为在进行映射时,它也会映射到正确的类型。TypeScript不会将值转换为适当的/声明的类型。请参阅,这是您的
      \u matchService
      如何检索日期的?如果它来自HTTP请求,您是否将它们转换为日期?您的MatchService需要返回JavaScript日期对象。我假设它正在返回字符串。我已经从我的MatchService添加了代码。我认为在进行映射时,它也会映射到正确的类型。TypeScript不会将值转换为适当的/声明的类型
      <div class="row">
          <div class="col-md-6 col-xs-12">
              <div *ngIf="lastMatch" class="card">
                  <div class="card__content">
                      <p>{{lastMatch.MatchDate | date:"short"}}</p>
                  </div>
              </div>
          </div>
          <div class="col-md-6 col-xs-12">
              <div *ngIf="nextMatch" class="card">
                  <div class="card__content">
                      <p>{{nextMatch.MatchDate}}</p>
                  </div>
              </div>
          </div>
      </div>
      
      getNextMatch() {
          return this.http.get(this._apiUrl + '/next')
              .map(res => <Match>res.json())
              .catch(this.handleError);
      }