【问题标题】:InvalidPipeArgument: 'Invalid Date' for pipe 'DatePipe'InvalidPipeArgument:管道“DatePipe”的“无效日期”
【发布时间】:2018-08-05 22:36:20
【问题描述】:

错误是

InvalidPipeArgument:管道“DatePipe”的“无效日期”。

我想在 p 日历(Primeng 组件)中显示 json 数据。我正在从 json 文件中获取数据并显示在输入字段中,但它不起作用。

如果可能,请提供 p-dropdown 和 p-radiobutton 的解决方案,以便在输入字段中显示 json 数据

demographic.component.html

<form [formGroup]="userform" (ngSubmit)="onSubmit(userform.value)">

<div class="ui-fluid">

    <p-panel header="Demograhics">


        <div class="ui-inputgroup">

                <label for="email" class="ui-md-2 control-label">Birthdate</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <p-calendar [(ngModel)]="date3" formControlName="birthdate"  [monthNavigator]="true" [defaultDate]="defaultdate" [yearNavigator]="true"   yearRange="1950:2030" [showIcon]="true" dateFormat="dd.mm.yy" name="calendar"></p-calendar> <span style="margin-left:35px">{{date3|date}}</span>       
                        </div>
                    </div>

                    <div class="ui-md-4">     
                        <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['birthdate'].valid&&userform.controls['birthdate'].dirty">
                            <i class="fa fa-close"></i>
                        Birthdate is required
                        </div>                                
                    </div>
        </div>


        <div class="ui-inputgroup">

                <label for="password" class="ui-md-2 control-label">Martial Status</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                                <p-dropdown [options]="Martials" formControlName="martialstatus" [(ngModel)]="selectedvalidid5" [style]="{'width':'150px'}" filter="true" name="something" placeholder="MartialStatus">
                                        <ng-template let-item pTemplate="selectedItem">


                                            <span style="vertical-align:middle">{{item.label}}</span>
                                        </ng-template>
                                        <ng-template let-Martial pTemplate="item">
                                            <div class="ui-helper-clearfix" style="position: relative;height: 25px;">

                                                <div style="font-size:14px;float:right;margin-top:4px">{{Martial.label}}</div>
                                            </div>
                                        </ng-template>
                                    </p-dropdown>          


                            </div>
                        </div>

                        <div class="ui-md-4">     
                            <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['martialstatus'].valid&&userform.controls['martialstatus'].dirty">
                                <i class="fa fa-close"></i>
                            Martial status is required
                            </div>


                    </div>
        </div>

        <div class="ui-inputgroup">

                <label for="password" class="ui-md-2 control-label">Gender</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <p-radioButton name="group2" value="Male" formControlName="gender" label="Male"  [(ngModel)]="val2" inputId="preopt1" name="something"></p-radioButton>
                            <p-radioButton name="group2" value="Female" formControlName="gender" label="Female"  [(ngModel)]="val2" inputId="preopt2" name="something"></p-radioButton>
                        </div>
                    </div>

                    <div class="ui-md-4">     
                        <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['gender'].valid&&userform.controls['gender'].dirty">
                            <i class="fa fa-close"></i>
                        Gender is required
                        </div>


                </div>
        </div>



        <div class="ui-inputgroup">

                <div class="ui-md-8 ui-md-offset-4">
                    <button pButton type="submit" label="Submit" [disabled]="!userform.valid"></button>
                        <button pButton type="button" (click)="count()" label="Cancel"></button>                           
                </div>
        </div>                     

    </p-panel>

</div>

</form>  

demographic.component.ts

import { Component, OnInit } from '@angular/core';
import * as jwt from 'angular2-jwt/angular2-jwt';
import { CardModule } from 'primeng/card';
import { CalendarModule } from 'primeng/calendar';
import { ScrollPanelModule } from 'primeng/scrollpanel';
import { Response } from '@angular/http/src/static_response';
import { CountryService} from './country-list.service';
import {SelectItem} from 'primeng/api';
import { Message } from 'primeng/components/common/api';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { PersonListService,Person, Demographic} from './person-list.service';


@Component({ 
  moduleId: module.id,
  selector: 'sd-demographicform',
  templateUrl: 'demographicform.component.html',
  styleUrls: ['demographicform.component.css']
})
export class DemographicFormComponent implements OnInit {



  date3: Date = new Date("{{ demographics?.Birthdate | date:dd.mm.yy }}");

  dates: Date[];

  rangeDates: Date[];

  minDate: Date;

  maxDate: Date;

  es: any;

  invalidDates: Array<Date>

  val2: string = 'Male';

  val3: string = 'Unmarried';

  text: string;

  ValidIds: SelectItem[];

  selectedvalidid2: string = '';

  Religions: SelectItem[];

  selectedvalidid3: string = '';

  BloodGroups: SelectItem[];

  selectedvalidid4: string = '';

  Martials: SelectItem[];

  selectedvalidid5: string = '';

  country: any;

  filteredCountriesSingle: any[];

  msgs: Message[] = [];

  userform: FormGroup;

  submitted: boolean;

  demographics: Demographic;



  constructor(private countryService: CountryService,private fb: FormBuilder,public personListService:PersonListService) { }

  filterCountrySingle(event) {
      let query = event.query;
      this.countryService.getCountries().then(countries => {
          this.filteredCountriesSingle = this.filterCountry(query, countries);
      });
  }

  filterCountry(query, countries: any[]):any[] {
    //in a real application, make a request to a remote url with the query and return filtered results, for demo we filter at client side
    let filtered : any[] = [];
    for(let i = 0; i < countries.length; i++) {
        let country = countries[i];
        if(country.name.toLowerCase().indexOf(query.toLowerCase()) == 0) {
            filtered.push(country);
        }
    }
    return filtered;
}
  ngOnInit() {

    this.getperson();
    //this.date3.setDate((new Date()).getDate() - 5);
    this.userform = this.fb.group({
        'nationality': new FormControl('', Validators.required),
        'birthdate': new FormControl('', Validators.required),
        'martialstatus': new FormControl('', Validators.required),
        'gender': new FormControl('', Validators.required),
        'height': new FormControl('', Validators.required),
        'valididtype': new FormControl('', Validators.required),
        'valididno': new FormControl('', Validators.required)

    }
);

    this.ValidIds = [
      {label: 'Adharcard', value: 'Adharcard'},
      {label: 'Pancard', value: 'Pancard'},
      {label: 'Driving Lincense', value: 'DrivingLincense'},
      {label: 'Passport', value: 'Passport'},

  ];

  this.Martials = [
    {label: 'Married', value: 'Married'},
    {label: 'Unmarried', value: 'Unmarried'},
    {label: 'Divorced', value: 'Divorced'},
    {label: 'Widowed', value: 'Widowed'},
    {label: 'Separated', value: 'Separated'},
];

  this.Religions = [
    {label: 'Hindu', value: 'Hindu'},
    {label: 'Islam', value: 'Islam'},
    {label: 'Christianity', value: 'Christianity'},
    {label: 'Sikhism', value: 'Sikhism'},
    {label: 'Buddhism', value: 'Buddhism'},
    {label: 'Jainism', value: 'Jainism'},
];

this.BloodGroups = [
  {label: 'A', value: 'A'},
  {label: 'A+', value: 'A+'},
  {label: 'B', value: 'B'},
  {label: 'C', value: 'C'},
  {label: 'AB', value: 'AB'},
  {label: 'O', value: 'O'},

];

       this.es = {
            firstDayOfWeek: 1,
            dayNames: [ "domingo","lunes","martes","miércoles","jueves","viernes","sábado" ],
            dayNamesShort: [ "dom","lun","mar","mié","jue","vie","sáb" ],
            dayNamesMin: [ "D","L","M","X","J","V","S" ],
            monthNames: [ "enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre" ],
            monthNamesShort: [ "ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic" ],
            today: 'Hoy',
            clear: 'Borrar'
        }


        let today = new Date();
        let month = today.getMonth();
        let year = today.getFullYear();
        let prevMonth = (month === 0) ? 11 : month -1;
        let prevYear = (prevMonth === 11) ? year - 1 : year;
        let nextMonth = (month === 11) ? 0 : month + 1;
        let nextYear = (nextMonth === 0) ? year + 1 : year;


        let invalidDate = new Date();
        invalidDate.setDate(today.getDate() - 1);
        this.invalidDates = [today,invalidDate];
    }
    getperson(){

        this.personListService.getDemographic()
        .subscribe(
         resp => this.demographics = resp.Demographics,

          //resp => this.addresses = resp.Addresses,

        );


   }
    onSubmit(value: string) {
        this.submitted = true;
        this.msgs = [];
        this.msgs.push({severity:'info', summary:'Success', detail:'Form Submitted'});
    }
}   

person.json

{

"Demographics" : {

            "ProfileId":1,
            "FirstName":"Vinit",
            "LastName":"Mapari",
            "Birthdate":"21/12/1996",
            "MartialStatus":"Unmarried",
            "Gender":"Male",
            "Height":"5ft2inch",
            "ValidIdType":"Pancard",
            "ValidIdNumber":"123",
            "Nationality":"Indian",
            "Religion":"Hindu",
            "BloodGroup":"A",
            "NearestRailwayStation":"Byculla"

        }
} 

【问题讨论】:

    标签: angular


    【解决方案1】:

    您收到错误“InvalidPipeArgument: 'Invalid Date' for pipe 'DatePipe'”,因为您尝试使用 DatePipe 格式化 undefined(而且语法也不正确)。

    首先您必须获取数据,然后指定您从响应中收到的日期。

    你可以的。

    在顶部。

    date3: string;
    

    当您收到数据时。

    getperson(){
    
        this.personListService.getDemographic()
        .subscribe(
         resp => {
            this.demographics = resp.Demographics;
            this.date3 = this.datePipe.transform(this.demographics.Birthdate, 'dd.mm.yy');
        });
    
    }
    

    您可以在我的other answer 中查看如何使组件中的 DatePipe 工作。

    但请记住,您必须先将日期更改为 ISO 标准日期 (YYYY-MM-DD),然后才能使用 DatePipe 对其进行格式化。如果您只是使用 json 文件来存储日期,请将其更改为 json 文件。如果您使用的是某些数据库,那么当您收到数据时,如果您正确设置了字段和 api 处理,您应该已经有了 iso 日期。

    【讨论】:

    • 非常感谢。我在 this.date3 = this.datePipe.transform(this.demographics.Birthdate, 'dd.mm.yy');错误是 [ts] 'string' 类型的参数不可分配给 '(error: any) => void' 类型的参数如何转换?请给我解决方案
    • 因为您将日期格式化为字符串。制作日期3:字符串;而不是日期。请参阅工作示例:stackblitz.com/edit/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多