Javascript 正在尝试在FireBase中显示shoppingcart对象中的项目总数

Javascript 正在尝试在FireBase中显示shoppingcart对象中的项目总数,javascript,angular,firebase,firebase-realtime-database,angularfire,Javascript,Angular,Firebase,Firebase Realtime Database,Angularfire,目标是遍历FireBase数据库中的所有项目,读取每个项目的数量,然后在前端显示总和。我遇到的问题是使用异步管道读取对象值。因为据我所知,使用异步需要一个数组。我尝试将购物车$设置为可观察的,以便async可以读取它。但是编译器告诉我,但是将它设置为AngularFireObject,这样就不允许在前端读取它。以下是相关代码 bs-navbar.component.ts import { Component, OnInit } from '@angular/core'; import { Aut

目标是遍历FireBase数据库中的所有项目,读取每个项目的数量,然后在前端显示总和。我遇到的问题是使用异步管道读取对象值。因为据我所知,使用异步需要一个数组。我尝试将
购物车$
设置为可观察的,以便async可以读取它。但是编译器告诉我,但是将它设置为AngularFireObject,这样就不允许在前端读取它。以下是相关代码

bs-navbar.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { AppUser } from '../models/app.user';
import { ShoppingCartService } from '../shopping-cart.service';
import { Observable } from 'rxjs';
import { ShoppingCart } from '../models/shopping-cart';
import { AngularFireObject } from '@angular/fire/database/database';


@Component({
  selector: 'bs-navbar',
  templateUrl: './bs-navbar.component.html',
  styleUrls: ['./bs-navbar.component.css']
})
export class BsNavbarComponent implements OnInit {
  appUser: AppUser
  cart$: Observable<ShoppingCart>

  constructor(public auth: AuthService, private shoppingCartService: ShoppingCartService) {
    auth.appUser$.subscribe(appUser => this.appUser = appUser)
  }

  logout() {
    this.auth.logout()
  }

  async ngOnInit() {
    this.cart$ =  (await this.shoppingCartService.getCart())  
  }
}

购物车服务

import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import { Product } from './models/product';
import { take, switchMap, map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { removeSummaryDuplicates } from '@angular/compiler';
import { ShoppingCart } from './models/shopping-cart';


@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {

  constructor(private db: AngularFireDatabase) { }

  private create() {
    console.log('Create a cart item was called')
    return this.db.list('/shopping-carts/').push({
      dateCreated: new Date().getTime()
    })
  }

  getItem(cartId: string, productId: string) {
    return this.db.object('/shopping-carts' + cartId + '/items' + productId)
  }

  async getCart(): Promise<AngularFireObject<ShoppingCart>> {
    let cartId = await this.getOrCreateCartId()
    console.log(this.db.object('/shopping-carts/' + cartId))
    return this.db.object('/shopping-carts/' + cartId)
  }

  private async getOrCreateCartId(): Promise<string> {
    let cartId = localStorage.getItem('cartId')
    if (cartId) return cartId

    let result = await this.create()
    localStorage.setItem('cartId', result.key)
    return result.key
  }

  async removeFromCart(product: Product) {
    let cartId = await this.getOrCreateCartId()
    let item$ = this.db.object('/shopping-carts/' + cartId + '/items/' + product.key)
    item$.snapshotChanges().pipe(take(1)).subscribe(item => {
      if (item.payload.exists()) item$.update({ product: product, quantity: item.payload.exportVal().quantity - 1 })
      else item$.set({ product: product, quantity: 1 })
    })
  }

  async addToCart(product: Product) {
    let cartId = await this.getOrCreateCartId()
    //Below we append the items to the shopping cart as a node below the original
    // shoppin-cart key
    let item$ = this.db.object('/shopping-carts/' + cartId + '/items/' + product.key)
    item$.snapshotChanges().pipe(take(1)).subscribe(item => {
      if (item.payload.exists()) item$.update({ product: product, quantity: item.payload.exportVal().quantity + 1 })
      else item$.set({ product: product, quantity: 1 })
    })
  }
}
从'@angular/core'导入{Injectable};
从'@angular/fire/database'导入{AngularFireDatabase,AngularFireObject};
从“./models/Product”导入{Product};
从'rxjs/operators'导入{take,switchMap,map};
从“rxjs”导入{Observable};
从'@angular/compiler'导入{removeSummaryDuplicates};
从“./models/ShoppingCart”导入{ShoppingCart};
@注射的({
providedIn:'根'
})
出口级购物车服务{
构造函数(私有数据库:AngularFireDatabase){}
私有创建(){
console.log('调用了创建购物车项目')
返回此.db.list(“/shopping carts/”).push({
dateCreated:new Date().getTime()
})
}
getItem(cartId:string,productId:string){
返回此.db.object('/shopping carts'+cartId+'/items'+productId)
}
async getCart():Promise

您服务中的
getCart()
函数返回一个
Promise
并将其分配给一个
可观察的
类型变量。如果您想使结果成为可观察的(我不明白它的意义)您可能应该使用RxJS中的
from
操作符从您的承诺创建一个可观察的。您服务中的
getCart()
函数正在返回一个
Promise
,您正在将其分配给一个
可观察的
类型变量。如果您想使结果成为一个可观察的(我不明白它的意义)您可能应该使用RxJs中的
from
操作符从您的承诺创建一个可观察的
import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import { Product } from './models/product';
import { take, switchMap, map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { removeSummaryDuplicates } from '@angular/compiler';
import { ShoppingCart } from './models/shopping-cart';


@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {

  constructor(private db: AngularFireDatabase) { }

  private create() {
    console.log('Create a cart item was called')
    return this.db.list('/shopping-carts/').push({
      dateCreated: new Date().getTime()
    })
  }

  getItem(cartId: string, productId: string) {
    return this.db.object('/shopping-carts' + cartId + '/items' + productId)
  }

  async getCart(): Promise<AngularFireObject<ShoppingCart>> {
    let cartId = await this.getOrCreateCartId()
    console.log(this.db.object('/shopping-carts/' + cartId))
    return this.db.object('/shopping-carts/' + cartId)
  }

  private async getOrCreateCartId(): Promise<string> {
    let cartId = localStorage.getItem('cartId')
    if (cartId) return cartId

    let result = await this.create()
    localStorage.setItem('cartId', result.key)
    return result.key
  }

  async removeFromCart(product: Product) {
    let cartId = await this.getOrCreateCartId()
    let item$ = this.db.object('/shopping-carts/' + cartId + '/items/' + product.key)
    item$.snapshotChanges().pipe(take(1)).subscribe(item => {
      if (item.payload.exists()) item$.update({ product: product, quantity: item.payload.exportVal().quantity - 1 })
      else item$.set({ product: product, quantity: 1 })
    })
  }

  async addToCart(product: Product) {
    let cartId = await this.getOrCreateCartId()
    //Below we append the items to the shopping cart as a node below the original
    // shoppin-cart key
    let item$ = this.db.object('/shopping-carts/' + cartId + '/items/' + product.key)
    item$.snapshotChanges().pipe(take(1)).subscribe(item => {
      if (item.payload.exists()) item$.update({ product: product, quantity: item.payload.exportVal().quantity + 1 })
      else item$.set({ product: product, quantity: 1 })
    })
  }
}
<h1>Shopping Cart</h1>
<ng-container *ngIf="cart$ | async as cart">
    <p>
        You have {{ cart.totalItemsCount}} items in your shopping cart.
    </p>
</ng-container>