【问题标题】:Cannot read property '1' of undefined angular 7无法读取未定义角度 7 的属性“1”
【发布时间】:2019-03-20 05:20:29
【问题描述】:

我正在使用 Angular 制作购物车组件。我使用 HttpClient 从本地服务器获取数据并将其存储在 products 数组中。我使用 *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;
  }

【问题讨论】:

    标签: angular undefined httpclient angular7


    【解决方案1】:

    尝试将 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));
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 谢谢,你说的就是异步调用,我会学习更多。
      猜你喜欢
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多