无法将“字符串”类型分配给“瞬间”类型错误

时间:2019-01-22 12:48:20

标签: angular typescript momentjs

我有一个这样的对象:

import { Moment } from 'moment';

export interface INewsletter {
    id?: number;
    creationDate?: Moment;
    email?: string;
}

export class Newsletter implements INewsletter {
    constructor(public id?: number, public creationDate?: Moment, public email?: string) {}
}

在一个地方,我需要从我使用的表单中获取日期,但是在第二种情况下,这给我带来了问题,我只需要从系统中获取日期,并将其用于新创建的对象中(没有错误,由于日期也是片刻,我不明白。)

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import * as moment from 'moment';
import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants';

import { INewsletter } from 'app/shared/model/newsletter.model';
import { NewsletterService } from '../../entities/newsletter/newsletter.service';

@Component({
    selector: 'jhi-footer',
    templateUrl: './footer.component.html'
})
export class FooterComponent implements OnInit {
    newsletter: INewsletter;
    isSaving: boolean;
    creationDate: string;

    constructor(private newsletterService: NewsletterService, private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.isSaving = false;
        this.creationDate = moment().format(DATE_TIME_FORMAT);
        this.newsletter = new Object(); 
(1)     this.newsletter.creationDate = moment().format(this.creationDate); 
(2)     this.newsletter.creationDate = this.creationDate;
    }

因此,在两种情况下(1)和(2)我都无法使其正常工作,而且我也不明白为什么。

1 个答案:

答案 0 :(得分:1)

在两种情况下,您都尝试将一个字符串分配给Newsletter.creationDate,该字符串需要一个Moment对象。

案例(1)可以通过用moment().format(this.creationDate);替换moment(this.creationDate);来工作,因为.format()的{​​{1}}方法返回一个字符串,如@Julien Metral所提到的