1
votes

I am trying to console the keys in firebase but it keeps giving me keys in a numbered order. This would be fine, but I have stored localStorage Id's in firebase and want to use that to access that specific node in the database.

I am using a service that has functions that add the local storage ID to firebase.

shopping-cart.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Product } from './product';
import { map, take} from 'rxjs/operators';


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

constructor(private database: AngularFireDatabase) { }

// creates new id for users
private create() {
return this.database.list('/shopping-cart').push({
  dateCreated: new Date().getTime(),
});

}

// get shopping cart from firebase
private getCart(cartId: string) {
  return this.database.object('/shopping-cart/' + cartId);
}

// get or create cart Id
private async getOrCreateToCart() {
  let cartId = localStorage.getItem('cartId');
  if (!cartId) {
     let result = await this.create();
     localStorage.setItem('cartId', result.key);
     console.log('this is result.key: ', result.key);
     return result.key;
  }
  console.log('this is cartId, result: ', cartId);
  return cartId;
}

   // actually add to cart
   async addToCart(product) {
     console.log('this is add to cart product: ', product);
    const cartId = await this.getOrCreateToCart();
    let usr;
    const test = this.database.list('/shopping-cart').valueChanges().subscribe(usrs => {
      usr = usrs;
    });
    console.log('This is test: ', test);
    // const item = this.database.object('/shopping-cart/' + cartId);
    // item.take(1).subscribe(items => {
    //   if (items.$exists()) {
    //     items.update({quantity: items.quantity + 1});
    //   } else {
    //     item.set({product: product, quantity: 1});
    //   }
    // });
   }


}

shoppng-cart.service.ts (relevant part of document)

 // actually add to cart
   async addToCart(product) {
     console.log('this is add to cart product: ', product);
    const cartId = await this.getOrCreateToCart();
    let usr;
    const test = this.database.list('/shopping-cart/' + cartId).valueChanges().subscribe(usrs => {
      usr = usrs;
    });
    console.log('This is test: ', test);
    // const item = this.database.object('/shopping-cart/' + cartId);
    // item.take(1).subscribe(items => {
    //   if (items.$exists()) {
    //     items.update({quantity: items.quantity + 1});
    //   } else {
    //     item.set({product: product, quantity: 1});
    //   }
    // });
   }

This is my html

 <div class="row">
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12" *ngFor='let user of usrs'>
         <div *ngIf="findType(user)">
           <h1>This is an object {{user.key}}</h1>

         </div>
         <div *ngIf="!findType(user)">
          <h1>This is not an object</h1>
        </div>
      </div>
    </div>

This is cart.component.ts

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
import { ProductListService } from '../productList.service';
import { AngularFireDatabase } from 'angularfire2/database';
import { ShoppingCartService } from '../shopping-cart.service';
import { Product } from '../product';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
  title = 'Products';
  add = 'Add to cart';
  products: any[];
  usrs: any[];
  keys: any[];
  productsNumber;


  constructor(private db: AngularFireDatabase, public cart: ShoppingCartService) {
    const result = db.list('/products').valueChanges().subscribe(products => {
      this.products = products;
    });

    const users = db.list('/shopping-cart').valueChanges().subscribe(usr => {
      this.usrs = usr;
      console.log(this.usrs);
    })
   }

   addToCart(product) {
     console.log('This is product object: ', product);
     return this.cart.addToCart(product);
   }

   findType(element, obj){
     if(typeof element === 'object') {
       return true;
     }

     return false;
   }

  ngOnInit() {
  }

}

My ultimate end goal is to find the cartId I saved in the database, add an array to it, and everytime someone clicks add to cart push that information in that specific user array.

For now, I am simply trying to access the cartId. My database is structured like

database structure

unimportant folder

-something inside folder 1
-something inside folder 2
-something inside folder 3

shopping-cart

- 01: 'test'
- -Lk234fkge (some random key I just made up but this is what the keys look like)
     - folder inside long key
- -Lk99388kkfl
     - folder inside long key

The problem is, every time I console the keys using Object.keys(obj) I get 0,1,2 instead of 0, (long key name), (other long key name). I've tried to use .list to attempt this, which to me seems like what I should be doing of all the things I've tried, but I can't get it to work. As you can see from looking at the service file, I've also tried using .object and then use take and subscribe to access the data but I kept getting an error that take is not a function. So, I decided to start from the top and simply just try to access the specific key. Any help would be greatly appreciated, I spent two days reading, doing tutorials, but most of them are out of date. I searched the firebase docs and couldn't find anything but examples that, with the limited knowledge I have of firebase, seemed not in line with what I was trying to accomplish. If you took the time to read this, thanks. Please add to the discussion if this is familiar to you.

1
I also facing the problem related to your code base. Please guide me because all I got are outdated materiel but fortunately I got this discussion. Problem isn't same as described here but I posted on the following link stackoverflow.com/questions/52474408/…" - Azhar

1 Answers

3
votes

.valueChanges() returns an array; that's why Object.keys is returning incrementing whole numbers 0, 1, 2, .... If you want to get at ids, you're going to need to use something like .snapshotChanges(); it's still in an array though (but will have a .key attribute), so if you really need an Object you're going to need to reduce it.

See the AngularFire docs for more information on using value vs. snapshot changes: https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md#angularfireaction---action-based-api