Angular - недопустимый формат даты и времени: 1292 Неверное значение даты и времени: '2019-10-31T00: 00: 00.000Z' - PullRequest
0 голосов
/ 01 октября 2019

Я занимаюсь разработкой клиентского портала. Laravel-5.8 - это бэкэнд, а Angular-7 - это фронтенд. У меня есть эта таблица:

CREATE TABLE `client_quotes` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `first_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `phone` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `address` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `business_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `truck_required` int(10) UNSIGNED NOT NULL,
  `truck_type` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT 'Flatbed 20 Ton',
  `quote_origin` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `quote_destination` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `commodity` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `loading_date` datetime DEFAULT NULL,
  `comment` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ApiController.php

public function createClientQuote(Request $request) {
  $request->validate([
  'first_name' => 'required',
  'last_name' => 'required',
  `enter code here`'email' => 'required|email',
  `enter code here`             
  'phone' => 'required|max:14',
  'business_name' => 'required',
  'truck_type' => 'required',
  'truck_required' => 'required',
  'quote_origin' => 'required',
  'quote_destination' => 'required',
  'commodity' => 'required',  
  'loading_date' => 'date|required' 
 ]);
 $clientquote = new ClientQuote([
  'first_name' => $request->first_name,
  'last_name'=> $request->last_name,
  'email' => $request->email,
  'phone' => $request->phone,
  'business_name' => $request->business_name,
  'address' => $request->address,
  'comment' => $request->comment,
  'truck_type' => $request->truck_type,
  'truck_required' => $request->truck_required,
  'quote_origin' => $request->quote_origin,
  'quote_destination' => $request->quote_destination,
  'commodity' => $request->commodity,  
  'loading_date' => $request->loading_date
 ]);
 $clientquote->save();

 return response()->json([
    'message' => 'Quote Successfully Sent!'
 ], 201);
}

This is my Model Class

ClientQuote.php

<?php
  namespace App;
  use Illuminate\Database\Eloquent\Model;
  use App\ClientQuote;

class ClientQuote extends Model
{
}

Angular

client-quote.component.ts

 @Component({
  selector: 'app-client-quotes-landing',
  templateUrl: './client-quotes-landing.component.html',
  styleUrls: ['./client-quotes-landing.component.scss']
 })
 export class ClientQuotesLandingComponent implements OnInit {

 public title = 'Places';
 public addrKeys: string[];
 public addr: object;

  formattedAddress = '';

  public form = {
   first_name : null,
   last_name : null,
   email : null,
   phone : null,
   address : null,
   business_name : null,
   truck_required : null,
   truck_type : null,
   quote_origin : null,
   quote_destination : null,
   commodity : null,
   loading_date : null,
   comment : null,
  };

 public error = {
  'first_name' : null,
  'last_name' : null,
  'email' : null,
  'phone' : null,
  'address' : null,
  'business_name' : null,
  'truck_required' : null,
  'truck_type' : null,
  'quote_origin' : null,
  'quote_destination' : null,
  'commodity' : null,
  'loading_date' : null,
  'comment' : null
 };

 constructor(
   private api: ApiService,
   private token: TokenService,
   private router: Router,
   private notify: SnotifyService,
   private zone: NgZone,
   ) {
   }

  ngOnInit() {
  }

  setAddress(addrObj) {
   this.zone.run(() => {
   this.addr = addrObj;
   this.addrKeys = Object.keys(addrObj);
  });
  }

 onSubmit(){
  this.notify.clear();
  var header = {
  'Content-Type': 'application/json'
 }
 return this.api.post('clientquotelanding', this.form, header).subscribe(
  error => this.errorHandle(error),
);
}

tokenHandler(data){
 this.notify.clear();
 console.log(data);
}

errorHandle(error){
 this.notify.clear();
 console.log(error);
 this.error = error.error.errors;
}
}

client-quote.component.html

    <form class="form-clientquote" #clientquoteForm=ngForm (ngSubmit)="onSubmit()">
    <div class="row">
      <div class="col-xs-12">
        <div class="col-xs-6">
        <label for="commodity">Commodity<span style="color:red;"> *</span></label>
        <input type="text" class="form-control" id="commodity" placeholder="Commodity" name="commodity" [(ngModel)]="form.commodity" #commodity="ngModel" [ngClass]="{'is-invalid' : commodity.invalid && ((commodity.dirty || commodity.touched) || clientquoteForm.submitted)}"   required>
         <div class="form-feedback" *ngIf="commodity.invalid && ((commodity.dirty || commodity.touched) || clientquoteForm.submitted)" class="invalid-feedback">
           <div style="color:red;" *ngIf="commodity.errors?.required"class="alert alert-danger">Commodity is required.</div>
         </div>
        </div>
        <div class="col-xs-6">
        <label for="loading_date">Loading Date<span style="color:red;"> *</span></label>
        <div class="input-group date" style="width: 100%;" >
        <mat-form-field>
        <input matInput [matDatepicker] = "picker" placeholder = "Choose a date" name="loading_date" [ngModel]="form.loading_date | date: 'dd/MM/yyyy'" (ngModelChange)=" form.loading_date= $event"  #loading_date="ngModel" [ngClass]="{'is-invalid' : loading_date.invalid && ((loading_date.dirty || loading_date.touched) || clientquoteForm.submitted)}"   required>
          <mat-datepicker-toggle matSuffix [for] = "picker"></mat-datepicker-toggle>
           <mat-datepicker #picker></mat-datepicker>
           </mat-form-field>
           <div class="form-feedback" *ngIf="loading_date.invalid && ((loading_date.dirty || loading_date.touched) || clientquoteForm.submitted)">
              <div style="color:red;" *ngIf="loading_date.errors?.required"class="alert alert-danger">Loading Date is required.</div>
              </div>
           </div>
         </div>
     </div>
   </div>

   <div class="row">
     <div class="col-xs-12">
       <div class="col-xs-12">
       <div class="btn-group">
          <button style="margin:5px" (keyup.enter)="onSubmit()" type="submit" class="btn btn-success" awNextStep> Get A Quote</button>
       </div>
       </div>
     </div>
   </div>
   </form>

Я использую указатель угловых материалов. Когда я нажал на кнопку отправки, я ожидал, что данные будут размещены в базе данных, и клиент будет в формате дд / мм / гггг. Вместо этого я получил ошибку, показанную ниже:

date error

Проблема связана с полем loading_date.

Как мне решитьэта ошибка?

1 Ответ

0 голосов
/ 25 октября 2019

попробуйте использовать момент

https://blog.angular.io/taking-advantage-of-the-angular-material-datepicker-237e80fa14b3

, он может в основном анализировать дату в любом необходимом формате.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...