5

我正在构建一个购物车,并且我使用了购物车服务,在该服务中,我将数量分配给产品/将产品添加到购物车。除了使用 take 来获取 observable item$ 的第一个实例之外,还有其他方法吗?

我正在正确导入 take 运算符,但它一直给我运行时错误。如果我不使用 take,那么分配的数量是一些随机整数而不是 1。

在以下代码中的可观察对象上使用 take() 时出现以下错误:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Product } from '../app/models/product';
import 'rxjs/add/operator/take';//tried this one too
import { take } from 'rxjs-compat/operator/take';

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

  constructor(private db: AngularFireDatabase) { }

  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 async getOrCreateCartId() {
    let cartId = localStorage.getItem('cartId');
    if (cartId) return cartId;

    let result = await this.create();
    localStorage.setItem('cartId', result.key);
    return result.key;

  }

  async addToCart(product: Product) { 
    let cartId = await this.getOrCreateCartId();
    let item$ = this.db.object('/shopping-carts/'+cartId+'/items/'+product.$key);
    item$.take(1).subscribe(item=>{
      if(item.$exists()) item$.update({quantity : item.quantity + 1});
      else item$.set({product : product , quantity : 1 });
    });
  }

}




Error: Uncaught (in promise): TypeError: item$.take is not a function. (In 'item$.take(1)', 'item$.take' is undefined) http://localhost:4200/main.js:1581:35 step@http://localhost:4200/main.js:1534:27 fulfilled@http://localhost:4200/main.js:1506:62 onInvoke@http://localhost:4200/vendor.js:46707:39 run@http://localhost:4200/polyfills.js:2483:49 http://localhost:4200/polyfills.js:3217:37 onInvokeTask@http://localhost:4200/vendor.js:46698:43 runTask@http://localhost:4200/polyfills.js:2533:57 drainMicroTaskQueue@http://localhost:4200/polyfills.js:2940:42 invokeTask@http://localhost:4200/polyfills.js:2845:40 invokeTask@http://localhost:4200/polyfills.js:3885:20 globalZoneAwareCallback@http://localhost:4200/polyfills.js:3911:27
resolvePromise — zone.js:814
(anonymous function) — zone.js:724
fulfilled — products.component.ts:11
onInvoke — core.js:14143
run — zone.js:138
(anonymous function) — zone.js:872
onInvokeTask — core.js:14134
runTask — zone.js:188
drainMicroTaskQueue — zone.js:595
invokeTask — zone.js:500
invokeTask — zone.js:1540
globalZoneAwareCallback — zone.js:1566
4

1 回答 1

8

我注意到的两个问题是:

  1. 进口 - 应该是:import { take } from 'rxjs/operators';

  2. 你应该使用pipe: 在你的情况下:

    item$.pipe(take(1)).subscribe(...)

在此处阅读有关它的更多信息

于 2018-12-04T14:02:02.950 回答