我正在尝试在Firebase中控制台密钥,但是它一直按编号顺序给我密钥。可以,但是我已经将localStorage ID存储在firebase中,并希望使用它来访问数据库中的特定节点。
我正在使用具有将本地存储ID添加到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
(文件的有关部分)
// 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});
// }
// });
}
这是我的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>
这是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() {
}
}
我的最终目标是找到我保存在数据库中的cartId,向其中添加一个数组,每当有人单击添加到购物车时,便将该信息推送到该特定用户数组中。
现在,我只是尝试访问cartId。我的数据库结构如下
数据库结构
不重要的文件夹
-something inside folder 1
-something inside folder 2
-something inside folder 3
购物车
- 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
问题是,每次我使用Object.keys(obj)控制台键时,我得到的是0,1,2而不是0(长键名)(其他长键名)。我尝试使用.list尝试此操作,在我看来,我尝试过的所有事情都应该做,但我无法使其正常工作。从查看服务文件可以看出,我也尝试使用.object,然后使用take和subscription来访问数据,但是我一直收到一个错误,认为take不是函数。因此,我决定从头开始,只是尝试访问特定的密钥。任何帮助将不胜感激,我花了两天时间阅读,编写教程,但其中大多数已过时。我搜索了Firebase文档,除了示例,在我对firebase的了解有限的情况下,这些示例似乎与我要完成的工作不符。如果您花时间阅读本文,谢谢。如果您对此很熟悉,请加入讨论。
最佳答案
.valueChanges()
返回一个数组;这就是Object.keys
返回递增整数0, 1, 2, ...
的原因。如果要获取ID,则需要使用.snapshotChanges()
之类的方法;虽然它仍然在数组中(但将具有.key
属性),所以如果您确实需要Object,则需要减少它。
有关使用值与快照更改的更多信息,请参见AngularFire文档:https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md#angularfireaction---action-based-api