2

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:-

enter image description here

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;
}

  • Please also post your HTML code and the JSON data being returned. –  Apr 06 '21 at 15:01
  • You need to add check for possible undefined value. Add in your `formatDate()` method the `else` condition and return a default value if `date = undefined`. – Dmitry S. Apr 06 '21 at 15:04
  • I think your `book` object is not typed and TypeScript cant recognize the `dateStart` property as `Date` type. – ShayD Apr 06 '21 at 15:04
  • @E.Maggini I updated my post.please check –  Apr 06 '21 at 15:07
  • @DmitryS. please clarify –  Apr 06 '21 at 15:08
  • just replace `book:any` to `book:Book` – ShayD Apr 06 '21 at 15:08
  • Thanks for providing additional information to your post by using the [edit] functionality. But please don't pollute your post with `EDIT:` or `UPDATE:` sections. [For future readers, posts need to be standalone, without any history. These sites are not forums, but intend to be libraries of canonical, high-quality, questions and answers. Future readers are not helped by seeing all kind of history.](https://meta.stackexchange.com/a/127655/316262) – 0xLogN Apr 06 '21 at 15:11
  • @ShayD Not working,same output. –  Apr 06 '21 at 15:13
  • 1
    Does your `Book.dateStart` property is of type Date? – ShayD Apr 06 '21 at 15:15
  • 1
    Can you please add the typings of the `Book` class – Batajus Apr 06 '21 at 15:16
  • also changing your data subscription from `subscribe(data=>{` to `subscribe((data:Book)=>{` is a better practice that can help you here – ShayD Apr 06 '21 at 15:18
  • @Batajus i updated my question.please check.. –  Apr 06 '21 at 15:19
  • @ShayD Book.dateStrat is property of ```Book``` class –  Apr 06 '21 at 15:20
  • I know. I just say that working with typed objects is cleaner – ShayD Apr 06 '21 at 15:22
  • Just for testing, Does changing `formatDate(date: Date)` to `formatDate(date:Date | undefined)` is working? – ShayD Apr 06 '21 at 15:25
  • @ShayD same issue.not working –  Apr 06 '21 at 15:39

1 Answers1

3

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

Batajus
  • 5,831
  • 3
  • 25
  • 38
  • this line error gone ``` dateStart:[this.formatDate(data.dateStart)],``` but still found error my formatData() fuction same as my post. –  Apr 06 '21 at 15:34
  • Error is: ``` error TS7030: Not all code paths return a value. 33 formatDate(date : Date){ ~~~~~~~~~~ ``` –  Apr 06 '21 at 15:35
  • @Batajus I've just realized that the `?` means optional and not nullable. can you explain a bit more? what is actually the different? – ShayD Apr 06 '21 at 15:35
  • Actually i don't know deeply which you question me. –  Apr 06 '21 at 15:38
  • @Linkon , (sorry. I have added the name in my last comment just to be clear) you should now add to your `if` statement the `else` statement and return the value you wish. you probably added the return type to your function `formatDate(date: Date):Date{` – ShayD Apr 06 '21 at 15:43
  • @Thank you..problem solved. now i understand. :) –  Apr 06 '21 at 15:49
  • @ShayD what exactly shall I explain more detailed? – Batajus Apr 06 '21 at 15:51
  • @Batajus Thanks. I found my answer here: https://stackoverflow.com/a/17220225/5107490 – ShayD Apr 06 '21 at 15:59