I have a db with some users, I have to add a new user to this list but I have a problem with the Date value. I take the fiel "nome(name)" and "cognome(surname)" with nome.value because they're a string but I have a problem with the anno_n(birth) because it's a Date type
COMPONENT.HTML
<div >
<h2 >Aggiungi un nuovo partecipante</h2>
<form (ngSubmit)="add(nome.value, cognome.value, anno_n.value)" (ngSubmit)="loadUser()" style="justify-content: center;">
<div >
<label for="inlineFormInputGroupUsername">Nome</label>
<div >
<input type="text" id="inlineFormInputGroupUsername" required #nome placeholder="Nome">
</div>
</div>
<div >
<label for="inlineFormInputGroupUsername">Cognome</label>
<div >
<input type="text" id="inlineFormInputGroupUsername" required #cognome placeholder="Cognome">
</div>
</div>
<div >
<label for="inlineFormInputGroupUsername">Data di nascita</label>
<div >
<input type="date" id="inlineFormInputGroupUsername" required ng-model="anno_n.value" #anno_n useValueAsDate placeholder="Data di nascita (GG/MM/AAAA)">
</div>
</div>
<div >
<button type="submit" >Salva</button>
</div>
</form>
</div>
COMPONENT.TS
add(nome: string, cognome: string, anno_n: string): void {
this.PartecipantiService.addP(nome, cognome, anno_n).subscribe(res => {
console.log(res);
this.loadUser();
})
}
export interface Partecipanti {
id: number;
nome: string;
cognome: string;
anno_n: Date;
}
SERVICE.TS
addP(nome: string, cognome: string, anno_n: string): Observable<any> {
return this.http.post<Partecipanti>(this.partecipantiUrl, {
nome: nome,
cognome: cognome,
anno_n: new Date(anno_n)
}, this.httpOptions).pipe(
tap((newPartecipante: Partecipanti) => this.log(`partecipante aggiunto w/ id=${newPartecipante.id}`)),
catchError(this.handleError<Partecipanti>('addP'))
);
}
CodePudding user response:
You're using an input of type "date" - this already returns a Date, and you are again converting it to date in your service. Remove the anno_n: new Date(anno_n) from your POST call and see if this works.
CodePudding user response:
Put a console.log in your service
addP(nome: string, cognome: string, anno_n: string): Observable<any> {
console.log(new Date(anno_n))
...
}
If it prints the correct date, then your problem is with the api, it probably doesn't accept a date object. Why bother converting it anyways? Just keep it as a string and convert it when you need it.
export interface Partecipanti {
id: number;
nome: string;
cognome: string;
anno_n: string;
}
addP(nome: string, cognome: string, anno_n: string): Observable<any> {
return this.http.post<Partecipanti>(this.partecipantiUrl, {
nome: nome,
cognome: cognome,
anno_n: anno_n
}, this.httpOptions).pipe(
tap((newPartecipante: Partecipanti) => this.log(`partecipante aggiunto w/ id=${newPartecipante.id}`)),
catchError(this.handleError<Partecipanti>('addP'))
);
}
