take() 有问题 属性

Having an issue with the take() property

我正在尝试使用密钥从 firebase 检索单个对象。我不想为 .subscribe() 方法实现 OnDestroy,而是想使用 take() 属性 来获取单个对象并完成它。

问题是我得到一个错误 "property take does not exist on type void" 并且控制台中的错误是 "Undefined is not an object"。我已经搜索过了,似乎无法找出解决方案。

constructor(
    private router: Router,
    private route: ActivatedRoute,
    private categoryService: CategoryService,
    private productService: ProductService) {
    this.categories$ = categoryService.getCategories();

    const id = this.route.snapshot.paramMap.get('id');
    if (id)  {
      this.productService.get(id).take(1).subscribe(p => this.product = p);
    }
  }

我已经导入了rxjs/add/operator/take。

编辑: 下面是我的 ProductService class

export class ProductService {

  constructor(private db: AngularFireDatabase) { }

  create(product) {
    return this.db.list('/products').push(product);
  }

  getAll() {
    return this.db.list('/products').snapshotChanges();
  }

  get(productId) {
    return this.db.object('/products/' + productId);
  }

}

这是我在控制台中得到的错误:

Error: Uncaught (in promise): TypeError: this.productService.get(id).take is not a function. (In 'this.productService.get(id).take(1)', 'this.productService.get(id).take' is undefined)

您似乎正试图在不是 Observable 的对象上调用 take

我的猜测是 this.productService.get(id) 是类型 AngularFireObject<T>):

export interface AngularFireObject<T> {
  query: DatabaseQuery;
  valueChanges(): Observable<T | null>;
  snapshotChanges(): Observable<SnapshotAction>;
  update(data: Partial<T>): Promise<void>;
  set(data: T): Promise<void>;
  remove(): Promise<void>;
}

您需要使用valueChanges(或snapshotChanges)来获取一个Observable:

this.productService.get(id).valueChanges().take(1).subscribe(p => this.product = p);

另请参阅:Retrieving data as objects