J L
J L

Reputation: 123

problem with key from firebase - return from my interface is undefined

So im doing the Online Course from Mosh Hamedami. I've been following it more or less but everything is working. I can Add Products to Firebase and Edit/Delete them. Now I want to implement a "shopping-cart" where I can add a specific CardId and add Items + quantity to that cardId

However I'm facing a problem where i want to add a Product to the firebase shopping-cart. Adding a shopping-cart with an cartId - timestamp works. Somehow I can't add an item to the cartId.

I got a Problem with the Observable I guess...

the Console Error is :

_core.js:6260 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'key' of undefined
TypeError: Cannot read property 'key' of undefined_
at ShoppingCartService.<anonymous> (shopping-cart.service.ts:51)

It tells me that my product from 'addToCart' is undefined.

  addToCart(product: Product) {
    this.shoppingCartService.addToCart(product);
    console.log(product);
  }

Also my complier tells me that take form .pipe(take(1)) is:

_error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type'Observable'.

somehow pipe(first()) works, but is delivering the same problem with the key.

I've tried a lot can't figure out my mistakes. Im new to Angular as well so..I would really appreciate any kind of tipps where I have to search for the Problem.

shopping-cart.service.ts

import {Injectable} from '@angular/core';
import {AngularFireDatabase} from "@angular/fire/database";
import {Product} from "./models/product";
import 'rxjs/add/operator/take';
import {take} from "rxjs-compat/operator/take";
import {pipe} from "rxjs";
import {Observable} from "rxjs";
import {first} from "rxjs/operators";


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

  constructor(private db: AngularFireDatabase) {
  }

  //create shopping cart in db + add date(timestamp)
  private create() {
    return this.db.list("/shopping-carts").push({
      dateCreated: new Date().getTime()
    });
  }

  private getCart(cartId: string) {
    return this.db.object('/shopping-carts/' + cartId);
  }

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

  //getting reference to shopping cart
  private async getOrCreateCartId(): Promise<string> {

    let cartId = localStorage.getItem('cartId');
    if (cartId) return cartId;
    // calls this.create and waits for the response
    let result = await this.create();
    //saves cartId in local storage and returns
    localStorage.setItem('cartId', result.key);
    return result.key;
  }

  //add new product to cart and safe localstorage
  async addToCart(product: Product) {
    const cartId = await this.getOrCreateCartId();
    //reference to products in firebase cart
    const item$ = this.getItem(cartId, product.key);

    item$.snapshotChanges().pipe(take(1)).subscribe((item: any) => {
      if (item) {
        item$.update({product: product, quantity: (item.quantity || 0) + 1});
      }
    });
  }
}

product.ts

export interface Product {
  key : string;
  title : string;
  price : number;
  category : string;
  imageURL : string;
}

html which is calling addToCart:

<div class="columns is-multiline is-narrow">
  <ng-container *ngFor="let p of filteredProductsByCategory">
    <div class="column is-one-third">
      <div class="card">
        <figure class="image is-square">
          <img [src]="p.imageURL" alt="{{p.title}}">
        </figure>
      </div>
      <div class="card-content">
        <p class="title"> {{p.title}}</p>
        <p class="subtitle">{{p.price | currency: "USD"}}</p>
        <div
             (click)="addToCart(product)"
             class="button is-outlined is-primary"> Add to Cart</div>
      </div>
    </div>
  </ng-container>
</div>

I could also upload my code to GitHub if needed! Thanks!!

Upvotes: 0

Views: 524

Answers (1)

servrox
servrox

Reputation: 239

// add new product to cart and safe localstorage
async addToCart(product: Product) { ... }

With a very high probability when calling addToCart the product is simply not set. You should check the point (*.component.ts or *.component.html?) where the function is called and and product should be set.

edit:

I guess you want to pass p instead of product. Try following:

<div
    (click)="addToCart(p)"
    class="button is-outlined is-primary"> Add to Cart</div>

Upvotes: 1

Related Questions