Cannot read property 'items' of null

Hi all. So I have been following Mosh’s Angular Course on shopping cart and I have been facing an issue in my console that says Cannot read property ‘items’ of null

After following the code I realized that a shopping cart object is not getting created on Firebase itself and the method that throws the error is this method in 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:any) => new ShoppingCart(x.items)));
  }

So can anyone please help me in finding out why my shopping cart object is not getting created in firebase? Any help would be highly appreciated.

2 Likes

This is one of the most asked question in this course surprisingly no one answered it.

Hi @pulchritudinous,

did you find the answer? I am also stuck with this.

Angular 12: Error: Uncaught (in promise): TypeError: Cannot read property ‘key’ of undefined
TypeError: Cannot read property ‘key’ of undefined.

Anyone found the solution to this question ?

Question link of Stackoverflow

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

this worked fine for me hope it also work for you.

1 Like

This is working:

async getCart(): Promise<Observable> {

let cartId = await this.getOrCreateCartId();

return this.db

  .object("/shopping-carts/" + cartId)

  .valueChanges()

  .pipe(map((x: ShoppingCart) => new ShoppingCart(x.items)));

}

1 Like

In shopping cart component just map with rxjs operator, it will convert object into array.

// Shopping cart class
import { map } from ‘rxjs/operators’;
export class ShoppingCartComponent implements OnInit {
cart$;
subscription: Subscription;

constructor(private shoppingCartService: ShoppingCartService) {}

async ngOnInit() {
this.cart$ = (await this.shoppingCartService.getCart())
.valueChanges()
.map((x) => new ShoppingCart(x.items))
.subscribe((cart) => {
console.log(‘This Values====>’, cart);
this.cart$ = cart;
});

// Shopping Cart Service

async getCart(): Promise<AngularFireObject> {
let cartId = await this.getOrCreateCartId();
return this.db.object(‘/shopping-carts/’ + cartId);
}