如何在Angular和Firebase中进行三向数据绑定?

时间:2019-10-09 01:46:48

标签: angular typescript firebase

我是angular和firebase的新手,所以我不清楚。 我现在正在专门在购物车页面上开发电子商务应用程序。 我在名为“ cart”的数据库中有一个集合,其中包含作为文档的产品,我将其数据存储在 cart.component.ts 文件中的对象的数组中。 然后,我将此数组循环到 cart.component.html 文件中,以将其数据显示为购物车项目。 所有这些都可以正常工作,但是我现在要做的是将' qty '的值与其数据库中的值链接起来,因此,当用户更改它时,它会在数据库中更改数据库。

这是(cart.component.ts)文件:

import { Component, OnInit } from '@angular/core';
import { Goods } from 'src/app/interfaces/goods';
import { CartService } from './../../services/cart.service';

@Component({
  selector: 'app-shopping-cart',
  templateUrl: './shopping-cart.component.html',
  styleUrls: ['./shopping-cart.component.scss']
})
export class ShoppingCartComponent implements OnInit {

  cartGoods: Array<Goods>;

  constructor(private cartSer: CartService) {}

  ngOnInit() {
    this.cartSer.getCartGoods().subscribe(data => {
      this.cartGoods = data.map(el => {
        return {
          id: el.payload.doc.id,
          ...el.payload.doc.data()
        };
      });
    });
  }

}

这是(cart.component.html)文件:

<ul class="cart">
  <li *ngFor="let good of cartGoods">
    <img [src]="good.img" [alt]="good.name">
    <h4 class="name"> {{ good.name | titlecase }} </h4>
    <strong class="price"> {{ good.price | currency }} </strong>
    <input class="qty" type="number" [(ngModel)]="good.qty">
  </li>
</ul>

1 个答案:

答案 0 :(得分:1)

警告语:

更新数据库以与数量保持同步可能不是一个好主意,因为-假设您是一个HTTP请求-这将意味着比实际需要更多的请求,从而减慢了您的应用程序的运行速度。考虑用户按下数字输入上的向上或向下箭头以更改数量。每次发生更改时,都会进行一次HTTP调用。用户可以单击“提交”或“保存”按钮没有任何选项来指示她已经完成设置数量了吗?

按照您的要求进行操作:

最简单的方法可能是绑定到ngModelChange指令的ngModel输出:

<input class="qty" type="number" [(ngModel)]="good.qty" 
        (ngModelChange)="saveQty(good)">

这样,您将执行saveQty并在模型值更改时将其传递给产品。从那里,您可以将good.qty保存在任意位置。

其他建议

我提供的功能可以使用,但是不容易扩展或测试。为了最大的长期利益,我建议您学习如何使用ReactiveForms API来控制组件类中的每种表单行为。对于此特定用例,我将使用FormArray动态创建购物车中物品所需的输入。