无法读取null的属性“ items”

时间:2019-01-24 13:18:11

标签: angular typescript

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

shopping-cart.ts

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

export class ShoppingCart {
    items: ShoppingCartItem[] = [];

}

shopping-cart-service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { Observable } from 'rxjs/observable';
import { Product } from './models/product';
import { take } from 'rxjs/operators';
import { map } from 'rxjs/operators';
import { ShoppingCart } from './models/shopping-cart';

@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {
  constructor(private db: AngularFireDatabase) { }
async getCart(): Promise<Observable<ShoppingCart>> {
    const cartId = await this.getOrCreateCartId();
    return this.db.object('/shopping-carts/' + cartId).valueChanges()
      .pipe(map(x => new ShoppingCart(x.items)));
  }

}

3 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,那么问题是您正在使用管道方法创建ShoppingCart的新实例。但是,您正在将x.items作为参数发送到ShoppingCart类,但是该类缺少如何处理参数的构造函数。因此,ShoppingCart.items始终是任何空数组,只要您不手动分配它。假设x是来自API的一些数据,并且x具有属性项。

尝试一下:

export class ShoppingCart {
  items: ShoppingCartItem[] = [];

  constructor(data?: Partial<ShoppingCart>) {
    Object.assign(this, data);
  }
}

并且:

return this.db.object('/shopping-carts/' + cartId).valueChanges()
  .pipe(map(x => new ShoppingCart(x)));

现在x.items将映射到ShoppingCart.items。

答案 1 :(得分:0)

更干净的方法是

shopping-cart.ts

export interface IShoppingCartList {
  items: ShoppingCartItem[];
}

export class ShoppingCart implements IShoppingCartList {
  constructor(public items: ShoppingCartItem[]) { }
}

export class ShoppingCartItem {
  x: string;
  y: number;
}

shopping-cart-service.ts

import { ShoppingCart } from './model/shopping-cart';

new ShoppingCart([{ x: 'Hi', y: 56 }])

答案 2 :(得分:0)

只需从项目中获取值并传递整个对象即可。

return this.db.object('/shopping-carts/' + cartId +'/items').valueChanges()
      .pipe(map(x => new ShoppingCart(x)) .