无法读取未定义 angular 7 的 属性“1”

Cannot read property '1' of undefined angular 7

我正在 angular.I 中制作购物车组件,使用 HttpClient 从本地服务器获取数据并将其存储在产品数组中。我使用 *ngFor 在 html 文件中显示数据。数据在 html 中正确显示,但是当我试图在组件文件中访问它以计算购物车总数时,它给了我这个错误。

Cart displayed and error

代码如下:

.html

<div class="container-fluid">
  <div class="card shopping-cart">
        <div class="card-header bg-dark text-light row">
           <div class="col-sm-6">
             <i class="fa fa-shopping-cart"></i>
            Shopping cart
          </div> 
          <div class="col-sm-6">
            <div class="justR">
                <a href="" class="btn btn-outline-info btn-sm pull-right ">Continue shopping</a>
              <div class="clearfix"></div>
            </div>

          </div>

        </div>
        <div class="card-body">
                <!-- PRODUCT -->
                <div *ngFor="let product of products;index as i">
                        <div class="row">
                                <div class="col-12 col-sm-12 col-md-2 text-center">
                                        <img class="img-responsive" src="{{product.prodUrl}}" alt="prewiew" width="120" height="80">
                                </div>
                                <div class="col-12 text-sm-center col-sm-12 text-md-left col-md-6">
                                    <h4 class="product-name"><strong>{{product.prodName}}</strong></h4>
                                    <h4>
                                        <small>{{product.prodDescription}}</small>
                                    </h4>
                                </div>
                                <div class="col-12 col-sm-12 text-sm-center col-md-4 text-md-right row">
                                    <div class="col-3 col-sm-3 col-md-6 text-md-right" style="padding-top: 5px">
                                        <h6><strong>₹{{product.prodPrice}} <span class="text-muted">x</span></strong></h6>
                                    </div>
                                    <div class="col-4 col-sm-4 col-md-4">
                                        <div class="quantity">
                                            <input type="number" [(ngModel)]="products[i].prodQuantity" step="1" max="99" min="1" value="{{products[i].prodQuantity}}" title="Qty" class="qty" size="4">

                                        </div>

                                    </div>
                                    <div class="col-2 col-sm-2 col-md-2 text-right">
                                        <button type="button" class="btn btn-outline-danger btn-xs">
                                            <i class="fa fa-trash" aria-hidden="true"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <hr>


                </div>


        <div class="justR">
        <div class="pull-right">
                <a (click)="updateCart()" class="btn btn-outline-secondary pull-right">
                    Update shopping cart
                </a>
            </div>
 </div>
        </div>
        <div class="card-footer">
          <div class="justR" style="margin: 10px">
            <a href="" class="btn btn-success pull-right">Checkout</a>
            <div class="pull-right" style="margin: 5px">
             Total price: <b>{{total}}</b>
             </div>
          </div>
        </div>
    </div>        

.ts 文件:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Cart } from 'src/app/cart/cartInterface';
import { RegisterService} from 'src/app/register.service';

 @Component({
 selector: 'app-cart',
 templateUrl: './cart.component.html',
 styleUrls: ['./cart.component.css']
 })


 export class CartComponent implements OnInit {

private url='http://localhost:3000/getcdata';
public products:Cart[];
errorMessage = '';
total:number;
constructor(private http:HttpClient,private registerService:RegisterService) 
{}



ngOnInit()
{
  this.http.get<Cart[]>(this.url).subscribe(res => {
  this.products = res;
  },
  error => console.error(error));
  this.total=getTotal(this.products);
  console.log(this.products[1].prodName);
}

updateCart()
{
    this.registerService.update(this.products)
    .subscribe(
    (      data: { message: string; }) => { console.log(data.message)},
    (      error: { statusText: string; }) => this.errorMessage = 
    error.statusText,     
    );
 }

}

 function getTotal(items:Cart[])
 {
   var total:number;
   var i=0;
   for(var item in items)
    {
     total=total+(items[i].prodPrice*items[i].prodQuantity);
     i++;
    }
  return total;
  }

我假设 console.log(this.products[1].prodName); 是抛出错误的行。您的 this.http.get<Cart[]>(this.url) 是异步发生的,并且会 运行 在 运行 在 subscribe 中调用回调之前的代码。网络请求(和其他异步事物)需要时间,并且 JavaScript 旨在通过将它们添加到事件循环来处理异步事物,以便在它们完成后 运行 稍后完成并且不会阻止其余代码正在执行。

所以 this.total=getTotal(this.products);console.log(this.products[1].prodName);this.products = res; 是 运行 之前得到 运行 导致 this.products 仍然是一个空数组当你尝试从中读取第二个元素。

阅读一些有关异步内容在 JavaScript 中的工作原理以及 Promises、async/await、and/or Observables 如何用于处理异步内容的文章可能会有所帮助(Angular 似乎严重依赖 Observables)。一开始可能有点混乱,但你会习惯处理异步的事情。

尝试将 ngOnInit 上的其他内容移动到回调中,如下所示:

    this.http.get<Cart[]>(this.url)
      .subscribe(res => {
        // This is called asynchronously when you get the response 
        this.products = res;
        this.total = getTotal(this.products);
        console.log(this.products[1].prodName);
      }, error => console.error(error));