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

时间:2019-03-20 05:20:30

标签: angular undefined httpclient angular7

我正在用angular制作一个购物车组件。我使用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;
  }

2 个答案:

答案 0 :(得分:0)

我假设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和/或Observables处理异步事物的信息可能会有所帮助(Angular似乎严重依赖Observables)。刚开始时可能会有些混乱,但是您已经习惯了处理异步事物。

答案 1 :(得分:0)

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