无法将接口与AngularFirebase一起使用 [英] Unable to use interface with AngularFirebase

查看:57
本文介绍了无法将接口与AngularFirebase一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试创建有角度的购物车时,我遇到了有关组件和服务的类型问题.我的服务当前返回AngularFireList<{}>,尽管我可以更改其类型,但这样做对其他方法和组件内部都有副作用.我想知道是否有一种有效的方法可以让我当前的界面成为类型.

While trying to create a shopping cart in angular, I've run into type issues regarding my components and services. My service currently returns AngularFireList<{}> and though I can change its type, doing so has side-effects in other methods and inside of my component. I'm wondering if there is an efficient way to allow my current interface to become the type.

我尝试将类型强制转换为Observable<ProdInterface>,这又解决了一个问题,同时又引入了另一个问题.

I've tried to cast the type as Observable<ProdInterface> which again, solves one issue while bringing in another.

我当前的界面是:

export interface ProdInterface {
    $key:string;
    color_way: string;
    name: string;
    id: number;
    description: string;
    photo:string;
    price:number;
    qty:number;
}

我正在寻求实现此方法,以便可以保留$key,这将允许我在firebase数据库中找到一个项目:

I'm looking to implement this method so that I can keep the $key which will allow me to find an item in my firebase database:

  async addToCart(product: ProdInterface){
    let cartId = await this.getOrCreateCart();
    let item$ = this.getItem(cartId, product.$key);
    item$.snapshotChanges().pipe(take(1)).subscribe(item => {
       item$.update({ product: product, 
                      quantity: (item.payload.exportVal().quantity || 0) + 1 });
    });
}

从firebase数据库中获取我所有的产品会返回一个Observable<{}>类型,该类型不具有我的addToCart方法所需的$key属性

Getting all of my products from my firebase database returns an Observable<{}> type which does not have $key attribute I need for my addToCart method

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

这意味着在使用该方法时,将返回错误的类型:

Which then means when using the method the wrong type is returned:

   this.products$ =  this.productService.getAll();

我的最终目标是可以将当前返回的getAll()类型映射到ProdInterface,以便可以在addToCart方法中使用它.

My end goal is such that I can map the current returned type of getAll() to my ProdInterface so that I can then use it inside of my addToCart method.

我会向正确的方向提供指导.

I would appreciate any guidance in the right direction.

谢谢!

推荐答案

以Firebase中的示例为例

With the example from the Firebase docs you could try this:

this.product$ = db.ref("products").orderByKey()
                  .once("value")
                  .pipe(
                  .map(snapshot => {
                      snapshot.forEach(childSnapshot) {
                      var key = childSnapshot.key
                      var childData = childSnapshot.val()
                      return {key, ...childData} 
                      }
                   }));

这篇关于无法将接口与AngularFirebase一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆