使用angular和firebase编辑/更新反应形式

时间:2018-12-28 09:05:59

标签: angular typescript firebase firebase-realtime-database angular-reactive-forms

我正在尝试通过elementId从另一个视图编辑/更新表单。

employee-list.comonent.ts(视图2):

 onEdit(empId:string){
this._router.navigate(['/RegisterEmployee',empId]);
//this.service.formData=Object.assign({},emp);
 }

单击它导航到具有选定元素ID的另一个视图,但是如何从选定元素的数据库中填充表单数据并更新Firebase数据库上的编辑数据

employee.component.ts(视图1)-反应形式

 ngOnInit() {
//this.resetForm();
this.form = this.formBuilder.group({
  fullName:new FormControl('',[Validators.required,Validators.pattern('[a-zA-Z][a-zA-Z ]+')]),
  designation: new FormControl('',[Validators.required,Validators.pattern('[a-zA-Z][a-zA-Z ]+')]),
  Email: new FormControl('',[Validators.required, Validators.email]),
  mobile: new FormControl('',[Validators.required, Validators.pattern('[0-9]*'),Validators.minLength(10),Validators.maxLength(10)])
});
 }

 /* submit the data to be added into database having 'employees' as the data 
 collection array*/
 onSubmit():void{
console.log(this.form.value);
this.router.navigateByUrl('/EmployeeList');
let data = Object.assign({},this.form.value);
if(this.form.value.id == null)
this.firestore.collection('employees').add(data);
else
this.firestore.doc('employees/'+this.form.value.id).update(data);
//this.resetForm(this.form);
this.toastr.success('Submitted successfully','Employee Register');
 }

我的服务如下: employee.service.ts

import { Injectable } from '@angular/core';
import { Employee } from './employee.model';
import { AngularFirestore } from '@angular/fire/firestore';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
formData : Employee;

constructor(private firestore:AngularFirestore) { }

/*Function to get added employees list from firebase database*/
getEmployees(){
let listOfEmployees = 
 this.firestore.collection('employees').snapshotChanges();
 return listOfEmployees;
  }
   }

我的界面形式: employee.model.ts

export class Employee {
id : string;
fullName: string;
Email: string;
mobile: string;
designation :string;
}

请对此提供帮助(Angular的新手,也是我使用Firebase的第一个项目)。

这是工作应用程序https://github.com/HusnaKhanam/MyApplication的git存储库

1 个答案:

答案 0 :(得分:1)

如果我理解正确,以下是使用数据填充表单的基本步骤:

在员工部分:

1)从类似于以下内容的url参数中读取ID:

  ngOnInit() {
    const param = this.route.snapshot.paramMap.get('id');
    if (param) {
      const id = +param;
      this.getProduct(id);
    }
  }

(注意:这是我的代码,您需要针对特定​​情况对其进行修改。)

2)从服务中获取与此类似的数据:

  getProduct(id: number): void {
    this.productService.getProduct(id)
      .subscribe(
        (product: Product) => this.displayProduct(product),
        (error: any) => this.errorMessage = <any>error
      );
  }

3)使用与此类似的代码更新表单上的数据:

  displayProduct(product: Product): void {
    this.product = product;

    // Update the data on the form
    this.productForm.patchValue({
      productName: this.product.productName,
      productCode: this.product.productCode,
      starRating: this.product.starRating,
      description: this.product.description
    });
  }