TypeError: "ctx.cart is undefined"

TypeError: "ctx.cart is undefined"

我正在开发披萨订购应用程序,目前我正在尝试实施购物车。

我为每个用户准备了一个购物车,每个购物车包含以下详细信息:cart.ts

import { CartItem } from './cartitem';

export class Cart {
    id: string;
    user: string;
    cartitems: CartItem[];
    grand_total: number;
}

用户可以从菜单中添加项目,这将成为我的购物车项目:cartitem.ts

import { Topping } from './topping';
export class CartItem {
    id: string;
    name: string;
    baseprice: number;
    toppings: Topping[];
    extraprice: number;
    quantity= 1;
    total: number;
}

因此,在将商品添加到购物车时,我在用户购物车的 API 端点上发出 PUT 请求,以放入购物车商品,作为响应,我将退回购物车那里的内容。

这是我的 cart.component.ts 的样子:

import { Component, OnInit, ViewChild, Inject, Injector } from '@angular/core';
import { CartItem } from '../shared/cartitem';
import { ActivatedRoute } from '@angular/router';
import { CartService } from '../services/cart.service';
import { map, catchError } from 'rxjs/operators';
import { Cart } from '../shared/cart';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.scss']
})
export class CartComponent implements OnInit {

  cart: Cart;
  // cartitems: CartItem[];

  constructor(
    private route: ActivatedRoute,
    private cartService: CartService,
    @Inject('BaseURL')public BaseURL) { }


  ngOnInit(): void {
    this.updateCart();

  }

  updateCart() {
    this.cartService.mysubject.subscribe((value) => {
      console.log(value);
      this.cartService.getItems().subscribe(response => {
        console.log("Response in cart comp:", response);

        let cartContent = new Cart();
        cartContent.cartitems = response['cartitems'];
        cartContent.id = response['id'];
        cartContent.grand_total = response['grand_total'];
        cartContent.user = response['user'];

        this.cart = cartContent;

        console.log("Cart is:", this.cart);

      });
    });
  }

}

现在的问题是我无法将 cart.component.html 端的数据与 'cart' 绑定,它会生成此错误 - ERROR TypeError: "ctx.cart is undefined".

我不知道如何解决这个问题。

编辑: 这是 cart.component.html:

<h2>Cart</h2>
<div>{{cart.user}}</div>
<mat-list dense>
    <mat-list-item *ngFor="let cartitem of cart.cartitems">
        <h2 matLine>Item: {{cartitem.name}}</h2>
        <p matLine>Base Price: ${{cartitem.baseprice}}</p>
        <p matLine [hidden]="cartitem.toppings == []">Extra Toppings:
            <mat-list matLine>
                <mat-list-item matLine *ngFor="let topping of cartitem.toppings">
                    <h4 matLine>{{topping.name}} : + ${{topping.rate}}</h4>
                </mat-list-item>
            </mat-list>
        </p>
        <button mat-mini-fab color="primary"><i class="fa fa-minus-circle"></i></button><div></div><button mat-mini-fab color="primary"><i class="fa fa-plus-circle"></i></button>
    </mat-list-item>

</mat-list>

<div [hidden]="!cart.cartitems"><h2>Subtotal: ${{cart.grand_total}}</h2></div>

<div [hidden]="cart.cartitems">
    <p> Your Cart is Empty!</p>
</div>

和错误日志:

ERROR TypeError: "ctx.cart is undefined"
    CartComponent_Template cart.component.html:2
    Angular 26
        executeTemplate
        refreshView
        refreshComponent
        refreshChildComponents
        refreshView
        refreshComponent
        refreshChildComponents
        refreshView
        refreshDynamicEmbeddedViews
        refreshView
        refreshComponent
        refreshChildComponents
        refreshView
        renderComponentOrTemplate
        tickRootContext
        detectChangesInRootView
        detectChanges
        tick
        next
        invoke
        onInvoke
        invoke
        run
        run
        next
        schedulerFn
    RxJS 5
    Angular 8
core.js:6185:19

我们没有 html 上下文,我们可以在其中查看您如何绑定 ctx,但我猜这是因为 ctx 在您的组件中不存在而您尝试绑定到它。当您访问未定义的对象 属性 时会抛出这种错误。

例如:

let someIncorrectObject = undefined;
someIncorrectObject.someValue // ERROR TypeError: "someIncorrectObject.someValue is undefined".

尝试像这样 html 中的绑定值 <div> {{ cart.id }}</div> 它应该可以工作。

附带说明一下,如果您这样做,代码质量会更容易、更好:

// now we dont need to explicitly instantiate new class
export interface Cart {
    id: string;
    user: string;
    cartitems: CartItem[];
    grand_total: number;
}

并在代码中执行以下操作

this.cart = {
    cartitems: response['cartitems'],
    id: response['id'],
    grand_total : response['grand_total'],
    user : response['user ']
}

添加的HTML显示HTML第2行的错误

<div>{{cart.user}}</div>

cart 定义为您的 TS 文件

cart: Cart;

内插值 cart.user 不可用,因为 cart 本身在初始化时未定义。 cart 稍后在订阅解析时填充。

一个快速的解决方法可能是将其包装在 ng-container 中并在其上使用 *ngIf

<ng-container *ngIf="cart">
  <h2...
  ...
  </div>
</ng-container>

cart 解决之前不会显示任何内容。

但是,为了提高代码质量,请在 TS

中用 getter 替换所有插值
get cartUser() { return (cart && cart.user) ? cart.user : null }

现在你的 HTML 会像

<div>{{cartUser}}</div>

同样,您会得到 cart.cartitems 的错误。使用这个 getter

get cartCartitems() { return (cart && cart.cartitems) ? cart.cartitems : [] }

并在 HTML

中将 cart.cartitems 的所有实例替换为 cartCartitems

希望对您有所帮助!

我用以下方法解决了这个问题:

cart: Cart = {} as Cart;

而不是:

cart: Cart;