Take 不是函数:Angular 7 | Observable.take 抛出运行时错误

Take is not a function : Angular 7 | Observable.take throws runtime error

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

我正在正确导入 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

我注意到的 2 个问题是:

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

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

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

here

上阅读更多相关信息