Angular Firebase database value Id of Items is showing undefined

23 Views Asked by At

Database value of Id items is showing undefined:

database value of Id items is showing undefined

I use angular 15.

here is model/product.ts

export interface Product{
    key: string;
    data:any;
    title: string;
    price: number;
    category: string|null;
    imageUrl:string;
}

here is product-card-component.ts

import { Component, Input } from '@angular/core';
import { Product } from '../models/product';
import { ShoppingCartService } from '../shopping-cart.service';

@Component({
  selector: 'product-card',
  templateUrl: './product-card.component.html',
  styleUrls: ['./product-card.component.css'] 
})
export class ProductCardComponent {
  
@Input('product') product: Product;
@Input('show-actions') showActions = true;
constructor(private cartService:ShoppingCartService){

}
addToCart(product:Product){
  this.cartService.addToCart(product);
 
}
}

Here is my shopping-cart.service

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { Product } from './models/product';
import {  take } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {
  product:Product[] = [];
  constructor(private db:AngularFireDatabase) { }
 private create(){
    return this.db.list('/shopping-carts/').push({
      dateCreated: new Date().getTime()
    });
  }
 
  private getItem(cartId: string, productId: string) {
    return this.db.object<any>('/shopping-carts/' + cartId + '/items/' + productId +'/');
  }

  private async getOrCreateCartId() {
    const cartId = localStorage.getItem('cartId');
    if (cartId) { return cartId; }
    let result = await this.create() as any;
    localStorage.setItem('cartId', result.key);
    return result.key;
}
  async addToCart(product:Product){
      let cartId = await this.getOrCreateCartId();
      
      let item$=  this.getItem(cartId, product.key);
            console.log( product.key);     // product.key show undefined 
      item$.valueChanges().pipe(take(1)).subscribe((item:any) => {
          if (item != null) {
           item$.update({ quantity: item.quantity + 1 })
                  }
                  else{
                    item$.set({product:product,quantity: 1})
                  }
                });
  


}
}

i have problem same Angular Firebase database value of Id is showing undefined but when i fix by answer its not work

0

There are 0 best solutions below