【问题标题】:How to create custom key Angular Firebase CRUD to make a Nested Child如何创建自定义键 Angular Firebase CRUD 以创建嵌套子项
【发布时间】:2019-11-25 16:09:42
【问题描述】:

我最近开始学习 Angular,希望帮助我了解如何制作特定顺序的嵌套子级。

This is how I want the table to look like.

However this is how the result that I have come up with so far.

来自“product.ts”的代码

export interface Product {
  $key: string;
  CategoryID: string;
  Description: string;
  Image: string;
  Name: string;
  Price: string;
  imageList: Array<string>;
}

来自“product.service.ts”的代码

import { Injectable } from '@angular/core';
import { Product } from './product';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from '@angular/fire/database';

@Injectable({
  providedIn: 'root'
})

export class ProductService {
  productsRef: AngularFireList<any>;
  productRef: AngularFireObject<any>;

  constructor(private db: AngularFireDatabase) { }

  /* Create Product */
  AddProduct(product: Product) {
    this.productsRef.push ({
      CategoryID: product.CategoryID,
      Description: product.Description,
      Image: product.Image,
      Name: product.Name,
      Price: product.Price,
      ImageList: product.imageList
    })
    .catch(error => {
      this.errorMgmt(error);
    });
  }

  /* Get Product */
  GetProduct(id: string) {
    this.productRef = this.db.object('products-list/' + id);
    return this.productRef;
  }

  /* Get Product List */
  GetProductList() {
    this.productsRef = this.db.list('products-list');
    return this.productRef;
  }

  /* Update Product */
  UpdateProduct(id, product: Product) {
    this.productRef.update({
      CategoryID: product.CategoryID,
      Description: product.Description,
      Image: product.Image,
      Name: product.Name,
      Price: product.Price,
      ImageList: product.imageList
    })
    .catch(error => {
      this.errorMgmt(error);
    });
  }

  /* Delete Product */
  DeleteProduct(id: string) {
    this.productRef = this.db.object('products-list/' + id);
    this.productRef.remove()
    .catch(error => {
      this.errorMgmt(error);
    });
  }

  /* Error Management */
  private errorMgmt(error) {
    console.log(error);
  }
} /* End of Export */

add-product.component.ts 中的代码

import { Component, OnInit, ViewChild } from '@angular/core';
import { COMMA, ENTER } from '@angular/cdk/keycodes';
import { MatChipInputEvent } from '@angular/material';
import { ProductService } from './../../shared/product.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { splitClasses } from '@angular/compiler';

export interface ImageList {
  name: string;
}

@Component({
  selector: 'app-add-product',
  templateUrl: './add-product.component.html',
  styleUrls: ['./add-product.component.css']
})

export class AddProductComponent implements OnInit {
  visible = true;
  selectable = true;
  removable = true;
  addOnBlur = true;
  imageArray: ImageList[] = [];
  @ViewChild('chipList', {static: false}) chipList;
  @ViewChild('resetProductForm', {static: false}) myNgForm;
  readonly separatorKeysCodes: number[] = [ENTER, COMMA];
  selectedCategoryType: string;
  productForm: FormGroup;
  CategoryType: any = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10'];

  constructor(
    public fb: FormBuilder,
    private productApi: ProductService
  ) { }

  ngOnInit() {
    this.productApi.GetProductList();
    this.submitProductForm();
  }

  /* Remove Duplciated Image Links */
  remove(prodimgList: ImageList): void {
    const index = this.imageArray.indexOf(prodimgList);
    if (index >= 0) {
      this.imageArray.splice(index, 1);
    }
  }

  /* Reactive Product Form */
  submitProductForm() {
    this.productForm = this.fb.group({
      prod_CategoryID: ['', [Validators.required]],
      prod_Description: ['', [Validators.required]],
      prod_Image: ['', [Validators.required]],
      prod_Name: ['', [Validators.required]],
      prod_Price: ['', [Validators.required]],
      prod_ImageList: [this.imageArray]
    });
  }

  /* Error Handling */
  public handleError = (controlName: string, errorName: string) => {
    return this.productForm.controls[controlName].hasError(errorName);
  }

  /* Reset Form */
  resetForm() {
    this.imageArray = [];
    this.productForm.reset();
    Object.keys(this.productForm.controls).forEach(key => {
      this.productForm.controls[key].setErrors(null);
    });
  }

  /* Submit Form */
  submitProduct() {
    if (this.productForm.valid) {
      this.productApi.AddProduct(this.productForm.value);
      this.resetForm();
    }
  }

}

【问题讨论】:

    标签: angular web


    【解决方案1】:

    我们可以使用 set 方法来创建 customNameIndex(as '01' etc.)

    注意:我已公开许可我的云 Firebase(在 RealTimeDatabase 中)。要获得与您在第二个屏幕截图中提到的相同的 JSON 类型,那么您的 imagesList 应该是一个对象而不是数组。如果您没有公共权限,则需要进行身份验证才能在实时数据库中插入行。

    我通过点击此链接配置了我的 firebase 和 angular。 firebase techdiaries。 (我将所有配置保存在 environment.ts 文件中)。我按照这个链接创建自定义密钥到谷歌火力基地。 creating customKey in firebase medium

    import { AngularFirestore } from '@angular/fire/firestore';
    import { AngularFireDatabase } from '@angular/fire/database';
    
     dbRef:any;
     constructor(private firestore: AngularFirestore,private fireDB: AngularFireDatabase) {
    
      }
      createData() {
          // for creating customKey 
          this.dbRef = this.fireDB.database.ref('images'); // i have collection named images in google firebase 
          this.dbRef.child('02').set({
            categoryId:"bond",
            Description:"bond",
            imageList:{
              "image1":"asdfasdf",
              "image2":"asdfasdfasdf"
            }
          });
       }
    

    以下链接可能会有所帮助。

    create custom key SO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-20
      • 2019-12-28
      • 2021-06-09
      • 2019-06-17
      相关资源
      最近更新 更多