无法将“字符串"类型分配给“瞬间"类型错误 [英] Type 'string' is not assignable to type 'Moment' error

查看:48
本文介绍了无法将“字符串"类型分配给“瞬间"类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象:

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

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

In one place I need to get the date from the form I'm using, but in the second case that is giving me the problem, I just need to get the date from the system and use it in the new created object (without the error, that I do not understand since the date is also a moment).

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)我都无法使其正常工作,而且我也不明白为什么.

So, in both cases (1) and (2) I can not make it work and I do not understand why.

推荐答案

在两种情况下,您都尝试将字符串分配给 Newsletter.creationDate ,该字符串期望 Moment 对象.

In both cases, you try to assign a string to Newsletter.creationDate, which expects a Moment object.

案例(1)可以通过将 moment().format(this.creationDate); 替换为 moment(this.creationDate); 作为来工作. moment 中的format()方法返回一个字符串,如 @Julien Metral

Case (1) could work by replacing moment().format(this.creationDate); by moment(this.creationDate); as the .format() method from moment returns a string, as mentionned by @Julien Metral

这篇关于无法将“字符串"类型分配给“瞬间"类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆