【问题标题】:I am not being able to access the properties defined in my model class from making service.ts by making an object of that class我无法通过制作该类的对象来访问我的模型类中定义的属性
【发布时间】:2018-11-20 06:31:04
【问题描述】:

在这里,x 无法访问 ShoppingCart 的属性 它显示的错误是类型 {} 上不存在属性项 我不知道我在哪里犯了我无法识别的错误

shopping-cart.service.ts

  async getCart(): Promise<Observable<ShoppingCart>> {
    let cartId = await this.getOrCreateCartId();
    return this.db.object('/shopping-carts/' + cartId)
    .valueChanges()
    .pipe(
      map(x => new ShoppingCart(x.items))

    );
  }


**ShoppingCart.ts**

import { Product } from './product';
import { ShoppingCartItem } from "./shopping-cart-item";

export class ShoppingCart {

    items: ShoppingCartItem[] = [];


    constructor(private itemsMap: { [productId: string]: ShoppingCartItem }) {
        this.itemsMap = itemsMap || {};

        for (let productId in itemsMap) {

            //we explicitly map each of the object to shoppingCart object 
            let item = itemsMap[productId];

            this.items.push(new ShoppingCartItem({
                // title: item.title,
                // imageUrl: item.imageUrl,
                // price: item.price,
                ...item,
                key: productId
            }));

        }
    }

【问题讨论】:

  • 试试 map(x =&gt; { new ShoppingCart(x.items) }) 我不是 100% 确定,但似乎可以。
  • 尝试了该过程它显示错误,因为类型'Observable'不可分配给类型'Observable'

标签: angular firebase observable angularfire5


【解决方案1】:

如果您仍然有这个问题,那么这可能会有所帮助...

async getCart(): Promise<Observable<ShoppingCart>> {
const cartId = await this.getOrCreateCartId();
return this.db.object('/shopping-cart/' + cartId).snapshotChanges()
.pipe(map(x => new ShoppingCart(x.payload.exportVal().items)));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2021-11-18
    • 2020-01-18
    • 1970-01-01
    相关资源
    最近更新 更多