【发布时间】:2019-09-06 21:40:58
【问题描述】:
让我以著名的书籍示例来解释我的问题。
我在 BookService.ts 中有一个基于 Book Model 的角度材料反应形式。当我更改此表单中的某些字段并将其提交到我的后端以使用 Angular HttpClient PUT 方法更新相应记录时,它没有更新我的数据库并返回错误。当我调试它时,它显示 ID 未定义,当我 console.log(BookForm.value) 我得到这个输出时:{$key: 1234, Title: "Book Title1", Topic: "Topic1"} ,无需说我的 Angular HttpClient PUT Restful API 需要该 ID 才能更新该特定记录在我的数据库表中。 Bellow 是我的简化模拟代码来解释它。
BookModel.ts File, My Model
export interface Book{
ID: number;
Title: string;
Topic: string;
}
BookService.ts File, My Service
BookForm: FormGroup = new FormGroup({
$key: new FormControl(null),
Title: new FormControl('', Validators.required),
Topic: new FormControl('', Validators.required),
});
UpdateBook(bookObj: Book): Observable<Book>
{
return this.http.put<Book>(`...api/book/${bookObj.ID}`, bookObj,{
headers: new HttpHeaders({
'Content-Type: 'application/json'
})
})
}
Note: This Throw Error, ID Undefined
Book-form.component.html File
<form [formGroup] = "BookService.BookForm" class="FormCls">
<mat-grid-list rowHeight="200px">
<mat-grid-tile>
<div class="form-controles-container">
<input type="hidden" formControlName="$key" />
<mat-form-field>
<input formControlName="Title" matInput placeholder="Title*" />
<mat-error>Title Needed</mat-error>
</mat-form-field>
<mat-form-field>
<input formControlName="Topic" matInput placeholder="Topic*" />
<mat-error>Topic Needed</mat-error>
</mat-form-field>
<div class="button-row">
<button mat-raised-button color="primary" type="submit" (click)="onSubmit()">Submit</button>
</div>
</div>
</mat-grid-tile>
</mat-grid-list>
</form>
Book-form.component.ts File
onSubmit(): void
{
BookService.UpdateBook(BookService.BookForm.value).subscribe(
b => alert(`Book Updated Successfully`),
err => alert(`Exception While Updating: ${err}`)
);
}
当然,我知道我需要一些如何将我的表单值转换为我的 Book 模型的方法,并确保在我将它传递给我的 http put 服务之前,我有那个 ID。但我不知道该怎么做,我在 Angular 和 Typescript 世界中都是新手,我正在学习。我喜欢在问之前阅读,所以浏览了很多文章,但没有一个对我有用。例如,我尝试了下面关于 stackoverfelow 的文章,但对我不起作用 Reactive Forms correctly convert Form Value to Model Object
我非常感谢您的专业人士,感谢您的时间和帮助。
【问题讨论】:
标签: asp.net angular typescript asp.net-core angular-material