我正在为我的技术学位开发一个angular项目,并尝试基于这篇文章编写DB过程:https://blog.logrocket.com/creating-a-crud-firebase-documents-in-angular/
首先,在teacher.component.html中,我在输入中添加了@angular/forms中的formsGroup,就像文章一样,但我将值添加到我的项目中,如下面的代码所示:
<form [formGroup]="this.form">
<div class="right">
<div>
<input mat-input type="text" name="username" placeholder="Username" formControlName="Username" autocomplete="off">
</div>
<div>
<input mat-input type="email" name="email" placeholder="email" formControlName="email" autocomplete="on">
</div>
<div>
<input mat-input type="tel" name="wpp" placeholder="wpp" formControlName="wpp" autocomplete="on">
</div>
<div>
<textarea name="bio" id="bio" placeholder="Write your bio" formControlName="bio" required></textarea>
</div>
<div>
<input mat-input type="number" min="1" step="any"name="perhour" placeholder="perhour" formControlName="perhour" autocomplete="on">
</div>
<div class="buttons">
<button mat-button (click)="onSubmit()">Submit</button>
</div>
</div>
</form>在teacher.component.js中,我在班主任中创建了这个变量
form = new FormGroup({
Username: new FormControl(''),
email: new FormControl(''),
wpp: new FormControl(''),
bio: new FormControl(''),
perhour: new FormControl(''),
completed: new FormControl(false)
//new: new FormControl(''),
})我还创建了onSubmit()方法来将数据发送到firestore数据库:
onSubmit() {
this.firestore.collection('Teacher').add({
field: this.form
//field: this.form.value.new,
})
.then(res => {
console.log(res);
this.form.reset();
})
.catch(e => {
console.log(e);
})
}最后,在方法onInit()中,我插入了以下函数:
ngOnInit(): void {
this.firestore.collection('Teacher').add({field:this.form})
}正如标题所说,我试着通过表格在火库的表格中插入一个数据,没有写任何东西,如果有人能帮助我,有建设性的批评和良好的建议,我非常感谢。
如果我写得不好,很抱歉,这是我第一次在这里写帖子。
发布于 2020-10-02 03:56:41
删除ngOnInit中的方法调用,因为它将始终添加一个空表单
this.firestore.collection('Teacher').add({field:this.form}).只留下代码onSubmit(),我认为可以完成这项工作。
发布于 2020-10-02 04:52:49
我的回答是考虑你使用的是Firestore,而不是Firebase,这是不同的产品。tou发布的链接有点奇怪,它在照片上有Firebase,但似乎使用了firestore。
这可能不是你的问题,但这一行不正确:
<form [formGroup]="this.form">改用这种方式:
<form [formGroup]="form">你的代码实现的方式,你将在你的收集表单对象,而不是它的值,在一个叫做' field‘的字段中
要保存表单值,只需执行以下操作:
onSubmit() {
this.firestore.collection('Teacher').add({...this.form.value})
.then(res => { // res here, is the document reference;
this.firestore.collection('Teacher').doc(res.id).update({id: res.id}); // Do this to keep the id in the document, it´s usefull to further edition.
console.log(res);
this.form.reset();
})
.catch(e => {
console.log(e);
})
}这样,您将拥有一个包含与您的表单相同名称的属性的文档。然后,当您需要编辑它时,您可以只对表单执行一个patch值,即:
this.firestore.collection('Teacher').doc(id).valueChanges.pipe(
map(values => {
this.form.patchValue(values)
})
)https://stackoverflow.com/questions/64161368
复制相似问题