简体   繁体   中英

Type 'undefined' is not assignable to type 'Date'

actually, I want to show the recorded Date on my page.for that, I have created a function for showing my recorded Date.but I am stuck when I found an unexpected error.

Here is my code:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { BookService } from 'src/app/services/book.service';

@Component({
  selector: 'app-update-book',
  templateUrl: './update-book.component.html',
  styleUrls: ['./update-book.component.css']
})
export class UpdateBookComponent implements OnInit {

  updateBookForm:FormGroup
  book:any
  constructor(private service:BookService,private route : ActivatedRoute,private   router:Router,private fb:FormBuilder) { }

  ngOnInit(): void {
    this.service.getBookById(this.route.snapshot.params.id).subscribe(data=>{
      this.book=data;

      this.updateBookForm = this.fb.group({
        id:[data.id],
        title:[data.title, Validators.required],
        author:[data.author, Validators.required],
        description:[data.description, Validators.compose([Validators.required, Validators.minLength(30)])],
        rate:[data.rate],
        dateStart:[this.formatDate (data.dateStart)],
        dateRead:[data.dateRead],
      })
    })
  }

  formatDate(date: Date){
    if(date){
      return new Date(date).toISOString().substring(0,10);
    }
  }

  onSubmit()
  {

  }

}


I am created here"formatDate "function but here is the main problem I am facing.

Here is my Error:-

在此处输入图像描述

how i will resolve this issue.please help.

Update

update-book.component.html


<div class="update-book">

    <form [formGroup]="updateBookForm"(ngSubmit)="onSubmit()">
        
        <div class="form-group">
          <label for="title" class="required">Title</label>
          <input type="text" class="form-control" id="title" formControlName="title" placeholder="Book Title">
        </div>
        <div class="form-group">
            <label for="author" class="required">Author</label>
            <input type="text" class="form-control" id="author" formControlName="author" placeholder="Book Author">
        </div>
        <div class="form-group">
            <label for="description" class="required">Description</label>
            <input type="text" class="form-control" id="description" formControlName="description" placeholder="Book Description">
        </div>
    
        <div class="row">
    
            <div class="col-md-4 col-xs-4 col-sm-4">
                <div class="form-group">
                    <label for="dateStart">Date Start</label>
                    <input type="date" class="form-control" id="dateStart" formControlName="dateStart" placeholder="Date Start">
                </div>
            </div>
            <div class="col-md-4 col-xs-4 col-sm-4">
                <div class="form-group">
                <label for="dateRead">Date Read</label>
                    <input type="date" class="form-control" id="dateRead" formControlName="dateRead" placeholder="Date Read">
                    </div>
            </div>
            <div class="col-md-4 col-xs-4 col-sm-4">
                <div class="form-group">
                    <label for="rate">Rate</label>
                    <input type="number" min="0" max="5" class="form-control" id="rate" formControlName="rate" placeholder="Rate">
                </div>
            </div>
    
        </div>
        <button class="btn btn-success" type="submit">UPDATE</button>
        <button class="btn btn-danger" type="submit" [routerLink]="['/books']" >CANCEL</button>
    </form>
    </div>

book.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Book } from '../interfaces/book'


@Injectable({
  providedIn: 'root'
})
export class BookService {

  readonly baseURL ="http://localhost:59750/api/Books"


  constructor(private http: HttpClient) { }


  getAllBooks()
  {
    return this.http.get<Book[]>(this.baseURL+"/GetBooks");
  }

  addBook(book: Book){
    return this.http.post(this.baseURL+"/AddBook/", book);
  }

  getBookById(id:number)
  {
        return this.http.get<Book>(this.baseURL+"/SingleBook/"+id);
  }

  upDateBook(book:Book){
    return this.http.put(this.baseURL+"/UpdateBook/"+book.id,book);
  }

  

}


Update

book.ts

export  interface Book
{
    id: number;
    title: string;
    description: string;
    author: string;
    rate?: number;
    dateStart?: Date;
    dateRead? : Date;
}

So regarding to your question and updates. Your problem is that dateStart is an optional property on you Book class. That's why you got the error message

Argument of type 'Date | undefined' is not assignable to parameter of type 'Date'

because this property can be undefined by design.

To change this you have two options in my opinion.

  1. Make the property dateStart to a "normal" property, so the compiler knows that the property is set, by removing the ? .

  2. You can try to cast the property to a Date

     dateStart:[this.formatDate(data.dateStart as Date)],

This should also prevent the error message, but you need to take care of a potential undefined value in you formatDate function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM