我面临一个关于 take(1) 不是 Angular Firebase 对象的函数的问题。我可以尝试使用 valuechages 或 snapshotchanges 但这对我没有帮助,因为我必须使用但还有其他问题。我使用的是 angular 6。
这是我的版本详细信息:-
Angular CLI: 6.2.5
Node: 8.12.0
OS: win32 x64
Angular: 6.1.10
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.8.5
@angular-devkit/build-angular 0.8.5
@angular-devkit/build-optimizer 0.8.5
@angular-devkit/build-webpack 0.8.5
@angular-devkit/core 0.8.5
@angular-devkit/schematics 0.8.5
@angular/cli 6.2.5
@angular/fire 5.1.0
@ngtools/webpack 6.2.5
@schematics/angular 0.8.5
@schematics/update 0.8.5
rxjs 6.3.3
typescript 2.9.2
webpack 4.20.2
在订阅方法的情况下,我面临同样的问题。
这是我的代码:-
import { Injectable, OnDestroy } from '@angular/core';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import 'rxjs/add/operator/take';
import { Product } from './models/product';
import { Subscription } from 'rxjs/Subscription';
import { take, map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ShoppingCartService {
suscription: Subscription ;
constructor(private db: AngularFireDatabase) { }
async addToCart(product: Product) {
this.updateItemQty(product, 1);
}
async removeFromCart(product) {
this.updateItemQty(product, -1);
}
async getCart() {
const cartId = await this.getOrCreateCartId();
return this.db.object('/shopping-cart/' + cartId)
}
async clearAllCart() {
const cartId = await this.getOrCreateCartId();
return this.db.object('/shopping-cart/' + cartId).remove();
}
private async updateItemQty(product: Product, change: number) {
const cartId = await this.getOrCreateCartId();
const item$ = this.getItem(cartId, product.$key);
item$.take(1).subscribe(item => {
const quantity = (item.quantity || 0) + change;
if (quantity === 0) { item$.remove(); } else { item$.update({
title: product.title,
imageUrl: product.imageUrl,
price: product.price,
quantity: quantity
});
}
});
}
private createCartId() {
return this.db.list('shopping-cart').push({
dateTime: new Date().getTime()
});
}
private async getOrCreateCartId(): Promise<string> {
let cartId = localStorage.getItem('cardId');
if (cartId) { return cartId; }
const cart = await this.createCartId();
cartId = localStorage.getItem('cardId');
if (cartId) { return cartId; }
localStorage.setItem('cardId', cart.key);
return cart.key;
}
private getItem(cartId, key) {
return this.db.object('/shopping-cart/' + cartId + '/items/' + key);
}
}
所以,我不能使用 snapshotchanges() 和 valuechanges(),因为那样我就无法使用或者我得到了错误,比如-item.quantity、item$.remove 和 item$.update。
为什么 take(1) 或 subscribe 不适用于 @angular/fire 5.1.0?
请提出建议或任何替代实施方式。