2016-04-30 6 views
0

Я больше не знаю, что реально.

Ив был с этой проблемой около 1 месяца его на основе учебник на udemy учебник здесь building an eccomerce store java spring mvc

В учебнике сам пришел с 0 файлов, вы в значительной степени должны скопировать его и молиться это работает

для по какой-то причине картотеки сохраняются в базе данных, однако они не привязываются к просмотру телеграммы после публикации. им с помощью agular JS для двухстороннего Databinding

я могу видеть, что данные сохраняющиеся так им приводят верить, что ошибка с угловым, но не могу быть вполне уверен, что

моя причина полагать, что это что ошибка будет более приспособлена к моделям при анализе через угловое и больше в программу. im говоря больше как scifi buff, чем программист, но это лучший способ описать что-то вроде этого.

спасибо, ребята, любая помощь будет оценен

Heres контроллера для углового

/** 
* Created by dwight on 4/8/2016. 
*/ 

var cartApp = angular.module ('cartApp', []); 

cartApp.controller('cartCtrl', function ($scope, $http) { 

    $scope.refreshCart = function() { 
     $http.get('/emusicstore/rest/cart/' + $scope.cartId).success(function (data) { 
      $scope.cart = data; 

     }); 

    }; 

    $scope.clearCart = function() { 
     $http.delete('/emusicstore/rest/cart/' + $scope.cartId).success($scope.refreshCart()); 
    }; 

    $scope.initCartId = function(cartId){ 
     $scope.cartId = cartId; 
     $scope.refreshCart(cartId); 
    }; 

    $scope.addToCart = function(productId){ 
     $http.put('/emusicstore/rest/cart/add/'+productId).success(function(){ 
      alert('Product successfully added to the cart!') 
     }); 
    }; 

    $scope.removeFromCart = function(productId){ 
     $http.put('/emusicstore/rest/cart/remove/'+productId).success(function(data){ 
      $scope.refreshCart(); 


     }); 
    }; 

    $scope.calGrandTotal = function(){ 
     var grandTotal=0; 

     for(var i=0; i<$scope.cart.cartItems.length; i++){ 
      grandTotal+=$scope.cart.cartItems[i].totalPrice; 
     } 

     return grandTotal; 
    }; 


}); 

heres the model 

    package com.emusicstore.model; 

import com.fasterxml.jackson.annotation.JsonIgnore; 

import javax.persistence.*; 

import java.io.Serializable; 

/** 
* Created by dwight on 4/4/2016. 
*/ 
@Entity 
public class CartItem implements Serializable{ 


private static final long serialVersionUID = -904360230041854157L; 

@Id 
@GeneratedValue 
private int cartItemId; 

@ManyToOne 
@JoinColumn(name = "cartId") 
@JsonIgnore 
private Cart cart; 

@ManyToOne 
@JoinColumn(name = "productId") 
private Product product; 


private int quantity; 
private double totalPrice; 

public int getCartItemId() { 
    return cartItemId; 
} 

public void setCartItemId(int cartItemId) { 
    this.cartItemId = cartItemId; 
} 

public Cart getCart() { 
    return cart; 
} 

public void setCart(Cart cart) { 
    this.cart = cart; 
} 

public Product getProduct() { 
    return product; 
} 

public void setProduct(Product product) { 
    this.product = product; 
} 

public int getQuantity() { 
    return quantity; 
} 

public void setQuantity(int quantity) { 
    this.quantity = quantity; 
} 

public double getTotalPrice() { 
    return totalPrice; 
} 

public void setTotalPrice(double totalPrice) { 
    this.totalPrice = totalPrice; 
} 

}

heres the dao or "data accessing object" 

    package com.emusicstore.dao.impl; 


import com.emusicstore.dao.CartItemDao; 
import com.emusicstore.model.Cart; 
import com.emusicstore.model.CartItem; 
import org.hibernate.Query; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 
import org.springframework.transaction.annotation.Transactional; 

import java.util.List; 

/** 
* Created by dwight on 4/18/2016. 
*/ 

@Repository 
@Transactional 
public class CartItemDaoImpl implements CartItemDao{ 

    @Autowired 
    private SessionFactory sessionFactory; 

    public void addCartItem(CartItem cartItem){ 
     Session session = sessionFactory.getCurrentSession(); 
     session.saveOrUpdate(cartItem); 
     session.flush(); 
    } 

    public void removeCartItem(CartItem cartItem){ 
     Session session = sessionFactory.getCurrentSession(); 
     session.delete(cartItem); 
     session.flush(); 


    } 

    public void removeAllCartItems(Cart cart){ 
     List<CartItem> cartItems = cart.getCartItems(); 

     for(CartItem item : cartItems){ 
      removeCartItem(item); 

     } 
    } 

    public CartItem getCartItemByProductId(int productId){ 
     Session session = sessionFactory.getCurrentSession(); 
     Query query = session.createQuery("from CartItem where productId = ?"); 
     query.setInteger(0, productId); 
     session.flush(); 

     return (CartItem)query.uniqueResult(); 

    } 

} 

и, наконец, по мнению

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> 
<%@include file="/WEB-INF/views/templates/header.jsp" %> 

<div class="container-wrapper"> 
    <div class="container"> 
     <section> 
      <div class="jumbotron"> 
       <div class="container"> 
        <h1>Cart</h1> 

        <p>Selected products in your shopping cart</p> 
       </div> 
      </div> 
     </section> 

    <section> 
     <div class="container" ng-app="cartApp"> 
      <div ng-controller="cartCtrl" ng-init="initCartId('${cartId}')"> 
       <div> 
        <a class="btn btn-danger pull-left" ng-click="clearCart()"><span 
          class="glyphicon glyphicon-remove-sign"></span>Clear cart</a> 
       </div> 
       <table class="table table-hover"> 
        <tr> 
         <th>Product</th> 
         <th>Unit Price</th> 
         <th>Quantity</th> 
         <th>Price</th> 
         <th>Action</th> 

        </tr> 

        <tr ng-repeat="item in cart.cartItems"> 
         <td>{{item.product.productName}}</td> 
         <td>{{item.product.productPrice}}</td> 
         <td>{{item.quantity}}</td> 
         <td>{{item.totalPrice}}</td> 
         <td><a href="#" class="label label-danger" ng-click="removeFromCart(item.product.productId)"> 
          <span class="glyphicon glyphicon-remove"></span>remove</a></td> 

        </tr> 
        <tr> 
         <th></th> 
         <th></th> 
         <th>Grand Total</th> 
         <th>{{calGrandTotal()}}</th> 
         <th></th> 

        </tr> 

       </table> 
       <a href="<spring:url value="/product/productlist"/> " class="btn btn-default">Continue Shopping</a> 
      </div> 
     </div> 

    </section> 
    </div> 
</div> 



<script src="<c:url value="/resources/js/controller.js"/> "></script> 
<%@include file="/WEB-INF/views/templates/footer.jsp" %> 

некоторые противные Светится TLE картинки cartItems error

спасибо больше Thats нуждался больной готов предоставить спасибо

ответ

0

на ваш взгляд, вы ссылаетесь cart.cartItems:

<tr ng-repeat="item in cart.cartItems"> 

, но в вашем контроллере, он не выглядит, как у вас есть код, который присваивает все, что вы извлекаете с сервера, в $ scope.cart.cartItems.

Если $ http.get возвращает именно то, что вам нужно, то присвоение данных в $ scope.cart.cartItems, вероятно, вам не хватает.

+0

Основываясь на том, что я дал, как бы я это сделал. У меня нет подсказки ... Я проверил код в ту ночь, и я даже изо всех сил нашел, что кто-то опубликовал код парня b в Интернете. Я не прошу, чтобы вы понимали мою программу целиком, но shold я явно добавляю calGrandTotal для цикла в $ scope.cart.cartItems.length в некотором роде, и если да, то как –

 Смежные вопросы

  • Нет связанных вопросов^_^