Angular 8-如何更新Firebase数据库

时间:2019-09-22 01:52:38

标签: angular typescript firebase firebase-realtime-database

我正在尝试更新载具列表,但由于遵循了Mosh的Udemy教程,它是Angular的过时版本,因此我不知道如何更新它。

服务代码(TS):

import { AngularFireDatabase, AngularFireList } from '@angular/fire/database';
import { Injectable } from '@angular/core';
import { Cars } from './component/vehicle-table/vehicle.services';

@Injectable({
  providedIn: 'root'
})

export class CarIdService {

  private dbPath = '/car';

  CarID: AngularFireList<Cars> = null;

  constructor(private db: AngularFireDatabase) {
    this.CarID = db.list(this.dbPath);
  }

  //Create
  create(carID) {
    this.db.list(this.dbPath).push(carID);
  }

  //Read
  getCarIdList(): AngularFireList<Cars>{
    return this.CarID;
  }

  //Update
  updateCarID(key: string, modelNum: any, 
    modelName: string, 
    regName: number,
    driverName: string, modelColor: string,
    carBrand: string ): Promise<void> {
    return this.CarID.update(key, modelNum);
  }
}

HTML:

<!--Form Add Vehicle-->
<form #f="ngForm" (ngSubmit)="save(f.value)">
    <div class="row">
        <div class="VehicleForm">

            <div class="form-group">
                <!--Model Number-->
                <label for="modelNum"> Model Number</label>
                <input required #modelNum="ngModel" ngModel name="modelNum" id="modelNum" type="number"
                    class="form-control">
            </div>
            <!--Error when blank-->
            <div class="alert alert-danger" *ngIf="modelNum.touched && modelNum.invalid">Model Number is required
            </div>

            <!--Model Name-->
            <div class="form-group">
                <label for="modelName"> Model Name</label>
                <input required #modelName="ngModel" ngModel name="modelName" id="modelName" type="text"
                    class="form-control">
            </div>
            <div class="alert alert-danger" *ngIf="modelName.touched && modelName.invalid">Model ame is required
            </div>

            <!--Reg Name-->
            <div class="form-group">
                <label for="regNum"> Registration Number</label>
                <input required #regNum="ngModel" ngModel name="regName" id="regNum" type="number"
                    class="form-control">
            </div>
            <div class="alert alert-danger" *ngIf="regNum.touched && regNum.invalid">Registration Number is required
            </div>

            <button class="btn btn-primary" [disabled]="!f.valid">Add to List</button>
        </div>

        <div class="VehicleForm2">
            <div class="form-group">
                <label for="driverName"> Driver Name</label>
                <input required #driverName="ngModel" ngModel name="driverName" id="driverName" type="text" class="form-control">
            </div>
            <div class="alert alert-danger" *ngIf="driverName.touched && driverName.invalid">Driver name is required </div>

            <div class="form-group">
                <label for="modelColor"> Color</label>
                <input required #modelColor="ngModel" ngModel name="modelColor" id="modelColor" type="text" class="form-control">
            </div>
            <div class="alert alert-danger" *ngIf="modelColor.touched && modelColor.invalid">Vehicle Color is required </div>

            <div class="form-group">
                <label for="carBrand"> Vehicle Brand</label>
                <input required #carBrand="ngModel" ngModel name="carBrand" id="carBrand" type="text" class="form-control">
            </div>
            <div class="alert alert-danger" *ngIf="carBrand.touched && carBrand.invalid">Vehicle Brand is required </div>

        </div>
    </div>
</form>

组件TS:

import { CarIdService } from './../../car-id.service';
import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'app-vehicle-list',
  templateUrl: './vehicle-list.component.html',
  styleUrls: ['./vehicle-list.component.css']
})
export class VehicleListComponent {

  constructor(private CarIdService: CarIdService){}
 
  save(carID){
    this.CarIdService.create(carID);
  }

}

我已经有了C.Create和R.Read,但是我不能执行U.Update和D.Delete。我已经尝试了其他一些功能,但似乎不适合我的代码。有人可以帮助我如何使用我在其中创建的Web应用程序更新Firebase数据库吗?

我将使用什么代码对数据库执行更新,就像单击行旁边的“编辑”一样。

1 个答案:

答案 0 :(得分:1)

您必须像在db: AngularFireDatabase中所做的那样使用create(carID)。在那里,您完成了push,要进行更新,您需要在列表上添加update呼叫:

  updateCarID(key: string, modelNum: any, 
    modelName: string, 
    regName: number,
    driverName: string, modelColor: string,
    carBrand: string ): Promise<void> {
    return this.db.list(this.dbPath).update(key, value);
  }

AngularFireList 的API可以找到here

通过API:

添加新项目:

const itemsRef = db.list('items');
itemsRef.push({ name: newName });

使用set替换列表中的项目:

const itemsRef = db.list('items');
// to get a key, check the Example app below
itemsRef.set('key-of-some-data', { size: newSize });

使用update

更新列表中的项目
const itemsRef = db.list('items');
// to get a key, check the Example app below
itemsRef.update('key-of-some-data', { size: newSize });

从列表中删除项目:

const itemsRef = db.list('items');
// to get a key, check the Example app below
itemsRef.remove('key-of-some-data');

删除整个列表:

const itemsRef = db.list('items');
itemsRef.remove();

在此tutorial中可以找到使用COLLECTIONS的Angular Firebase CRUD的完整示例。

该示例处理用户。

创建:

createUser(value, avatar){
  return this.db.collection('users').add({
    name: value.name,
    nameToSearch: value.name.toLowerCase(),
    surname: value.surname,
    age: parseInt(value.age),
    avatar: avatar
  });
}

阅读:

getPeople(){
  return new Promise<any>((resolve, reject) => {
    this.afs.collection('/people').snapshotChanges()
    .subscribe(snapshots => {
      resolve(snapshots)
    })
  })
}

更新

updateUser(userKey, value){
  value.nameToSearch = value.name.toLowerCase();
  return this.db.collection('users').doc(userKey).set(value);
}

删除:

deleteUser(userKey){
  return this.db.collection('users').doc(userKey).delete();
}