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

Date object being treated as string in template

我正在尝试使用 Angular2 日期管道来格式化日期。我有这个 class 作为我对象的模型:

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

    constructor(
        id: number,
        matchDate: Date
) {
        this.Id = id;
        this.MatchDate = matchDate;
    }
} 

然后我将 Match 对象获取到我的组件:

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

在我的模板中,我尝试显示匹配日期:

<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>

使用 {{nextMatch.MatchDate}} 时,我得到了正确的日期,但格式不符合我的要求。如果我使用 {{lastMatch.MatchDate | date:"short"}} 我会收到一条错误消息:

Invalid argument '2016-02-01T18:30:00' for pipe 'DatePipe'

MatchDate 不应该是 Date 对象,而不是字符串吗?

编辑:

这是我的 MatchService 的一部分:

getNextMatch() {
    return this.http.get(this._apiUrl + '/next')
        .map(res => <Match>res.json())
        .catch(this.handleError);
}

我认为您的服务没有 return 日期。如果您从 HTTP 请求中获取日期,则没有本地支持从响应中获取日期,因为 JSON 格式不提供对日期的支持。

有关详细信息,请参阅此问题: