首页 > 解决方案 > Spring 应用程序中的 AngularJS 控制器在亚马逊 AWS 上不起作用

问题描述

我有一个带有以下控制器的 spring 应用程序,它可以在 localhost 上运行(它会出现以下错误,但它的工作原理永远不会少 -

angular.min.js:13620 TypeError: Cannot read property 'cartItems' of undefined
    at ChildScope.$scope.calGrandTotal (controller.js:34)
    at fn (eval at compile (angular.min.js:14540), <anonymous>:4:230)
    at expressionInputWatch (angular.min.js:15679)
    at Scope.$digest (angular.min.js:17221)
    at Scope.$apply (angular.min.js:17501)
    at bootstrapApply (angular.min.js:1696)
    at Object.invoke (angular.min.js:4551)
    at doBootstrap (angular.min.js:1694)
    at bootstrap (angular.min.js:1714)

)

当我在 Amazon AWS 上的 elstastic beanstalk(在汤姆猫上)上午餐应用程序时,它根本不起作用,它显示以下错误:

angular.min.js:13620 TypeError: Cannot read property 'cartItems' of undefined
    at ChildScope.$scope.calGrandTotal (controller.js:34)
    at fn (eval at compile (angular.min.js:14540), <anonymous>:4:230)
    at expressionInputWatch (angular.min.js:15679)
    at Scope.$digest (angular.min.js:17221)
    at Scope.$apply (angular.min.js:17501)
    at bootstrapApply (angular.min.js:1696)
    at Object.invoke (angular.min.js:4551)
    at doBootstrap (angular.min.js:1694)
    at bootstrap (angular.min.js:1714)
    at angularInit (angular.min.js:1604)

Failed to load resource: the server responded with a status of 404 ()
angular.min.js:13620 TypeError: Cannot read property 'cartItems' of undefined
    at ChildScope.$scope.calGrandTotal (controller.js:34)
    at fn (eval at compile (angular.min.js:14540), <anonymous>:4:230)
    at expressionInputWatch (angular.min.js:15679)
    at Scope.$digest (angular.min.js:17221)
    at Scope.$apply (angular.min.js:17501)
    at done (angular.min.js:11600)
    at completeRequest (angular.min.js:11813)
    at XMLHttpRequest.requestLoaded (angular.min.js:11741)

控制器:

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

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

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

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

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

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

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

    $scope.calGrandTotal = function () {
        var grandTotal=0;
        var lenght = $scope.cart.cartItems.length;

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

        return grandTotal;
    };
});

看法:

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

<div class="container-wrapper">
    <div class="container">


                <div class="container">
                    <h1>Cart</h1>

                    <p>All the selected products in your shopping cart</p>
                </div>
            </div>


        <section class="container" data-ng-app="cartApp">
            <div data-ng-controller = "cartCtrl" data-ng-init="initCartId('${cartId}')">
            <div>
                <a class="btn btn-danger pull-left" data-ng-click="clearCart()"><span
                        class="glyphicon glyphicon-remove-sign"></span>Clear Cart</a>
                        <a href="<spring:url value="/order/${cartId}"/>"
                   class="btn btn-success pull-right"><span class="glyphicon-shopping-cart glyphicon"></span> Check out
                </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 data-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" data-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>
        </section>

    </div>

    <script>


    </script>


<div class="container-wrapper">
    <div class="container">


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

在本地主机上,它有我上面所说的错误,但是一切正常,但在弹性豆茎上它根本不工作。

购物车资源:

package com.myWebPage.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.myWebPage.model.Cart;
import com.myWebPage.model.CartItem;
import com.myWebPage.model.Customer;
import com.myWebPage.model.Product;
import com.myWebPage.service.CartItemService;
import com.myWebPage.service.CartService;
import com.myWebPage.service.CustomerService;
import com.myWebPage.service.ProductService;

@Controller
@RequestMapping("/rest/cart")
public class CartResources {

    @Autowired
    private CartItemService cartItemService;

    @Autowired
    private CartService cartService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private ProductService productService;

    @RequestMapping("/{cartId}")
    public @ResponseBody Cart getCartById(@PathVariable(value = "cartId") int cartId) {
        return cartService.getCartById(cartId);
    }

    @RequestMapping(value = "/add/{productId}", method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public void addItem(@PathVariable(value = "productId") int productId, @AuthenticationPrincipal User activeUser) {

        Customer customer = customerService.getCustomerByUsername(activeUser.getUsername());
        Cart cart = customer.getCart();
        Product product = productService.getProductById(productId);
        List<CartItem> cartItems = cart.getCartItems();

        for (int i = 0; i < cartItems.size(); i++) {
            if (product.getProductId() == cartItems.get(i).getProduct().getProductId()) {
                CartItem cartItem = cartItems.get(i);
                cartItem.setQuantity(cartItem.getQuantity() + 1);
                cartItem.setTotalPrice(product.getProductPrice() * cartItem.getQuantity());
                cartItemService.addCartItem(cartItem);

                return;

            }
        }
        CartItem cartItem = new CartItem();
        cartItem.setProduct(product);
        cartItem.setQuantity(1);
        cartItem.setTotalPrice(product.getProductPrice() * cartItem.getQuantity());
        cartItem.setCart(cart);
        cartItemService.addCartItem(cartItem);
    }

    @RequestMapping(value = "/remove/{productId}", method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public void removeItem(@PathVariable(value = "productId")int productId) {
        CartItem cartItem = cartItemService.getCartItemByProductId(productId);
        cartItemService.removeCartItem(cartItem);
    }
    @RequestMapping(value = "{CartId}", method = RequestMethod.DELETE)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public void clearCart(@PathVariable(value = "carttId")int cartId) {
        Cart cart = cartService.getCartById(cartId);
        cartItemService.removeAllCartItems(cart);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Illegal request, please verify your payload")
    public void handleClientErrors(Exception e) {}

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR, reason="Internal server error")
    public void handleServerError(Exception e) {}

}

购物车控制器:

package com.myWebPage.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.myWebPage.model.Customer;
import com.myWebPage.service.CustomerService;

@Controller
@RequestMapping("/customer/cart")
public class CartController {

    @Autowired
    private CustomerService customerService;

    @RequestMapping
    public String getCart(@AuthenticationPrincipal User activeUser) {
        Customer customer = customerService.getCustomerByUsername(activeUser.getUsername());
        int cartId = customer.getCart().getCartId();

        return "redirect:/customer/cart/"+cartId;
    }

    @RequestMapping("{cartId}")
    public String getCartRedirect(@PathVariable (value="cartId")int cartId, Model model) {
        model.addAttribute("cartId",cartId);

        return "cart";
    }
}

标签: angularjsamazon-web-servicesspring-mvcamazon-elastic-beanstalk

解决方案


var lenght = $scope.cart.cartItems.length; // typo var length

检查 $scope.cart 是否已定义或初始化


推荐阅读