如何将POJO插入Angular的模型?

问题描述 投票:3回答:4

我习惯在MVC模式视图中看到,控制器和模型分开,现在很多我怎么看模型在控制器中实现,对我来说这种做法不尊重MVC模式。

就我而言,我想要的是例如:

POJO车:

    public class Car
    {
     private int price;
     private int doors;

     public Car (int px, int dr)
     {
        this.price = px;
        this.doors = dr;
    }
   }

并在我的java程序中实例化之后

Car car = new Car(1000, 4);

现在,我该如何将这个对象放入Angular的模型中呢?

提前致谢。

java angularjs
4个回答
3
投票

我通常使用以下模式

angular.module('yourServiceName.car.model', [])
.factory('Car', function() {
    function Car(car) {
        /* extend with lodash.
         * Since this is a POJO, don't transform anything you dont need.
         */
        _.assign(this, car, this); 
    }

    Car.Enums = {SOME:1, ENUM:2, YOU:3, MIGHT:4, NEED:5};

    Car.prototype.method = function() {
        /* some model specific method.
         * don't throw REST or UI things here tho.
         */
    } 

    Car.create = {
        fromJSON: function(json) {
            /* only use this for JSON missing transformations, like
             * 'Y'|'N' to true|false
             * dateString to Date instance
             */
            json.startDate = Date.parse(json.startDate); or something.

            // I want to see 'Car' in my debug window, instead of 'Object'
            return new Car(json);
        }
    }

    return Car;
});

然后在您的API服务上

angular.module('yourService.car.rest', [
    'yourService.car.model'
])
.factory('carApi', function(baseURL, Car) {
    var path = baseURL+'/car'
    var Routes = {
            CREATE : path,
            LIST   : path+'/%s',
            DETAILS: path+'/%d'
        };

    function getCar(id, params) {
        // this should blowup if id is not a number
        var url = sprintf(Routes.DETAILS, id);
        return $http.get(url, params).then(function(response.data) {
            // if now JSON transformations are done
            // return new Car(response.data);

            return Car.create.fromJSON(response.data);
        });
    }

    function listCars(ids, params) {
        ids = ids || [];
        var _ids = ids.join(',');
        var url = sprintf(Routes.LIST, _ids);
        return $http.get(url, params).then(function(response) {
            return _.map(response.data, Car.create.fromJSON);
        });
    }

    function createCar(oCar) {
        /* Hungarian notation indicates I expect an instance of 'Car'
         * And not just any object
         */

        $http.post(Routes.CREATE, {data: oCar});
    }

    return  {list:listCars, get:getCar, create:createCar};
});

所以最后在你的控制器中,你会有类似的东西

angular.module('yourProject.ui.car.list', [
    'yourServiceName.car.model',
    'yourServiceName.car.rest'
])
.controller('ListCarsController', function ListCarsCtrlr(carsApi, Car) {
    $scope.ids = [1, 2, 3];

    $scope.load = function() {
        var params = {}; // anything else you need to pass
        carsApi.list(ids, params).then(function(cars) {
            $scope.cars = cars; // all of these are now instanceof Car
        })
    }
});

你的控制器最终就像这样简单:

enter image description here

如果你需要Viewmodel,你甚至可以把它拿出来

angular.module('yourProject.ui.car.list.viewmodel', [
    'yourService.car.model'
])
.factory('CarItemViewmodel', function CarItemVM() {
    function CarItemViewmodel(oCar) {
        // do some flattening or something you can unit test
        this.price = oCar.additionalAttributes.somethingDeep.price;
        this.ammount = oCar.someOtherStuff[0].quantity;
    };

    return CarItemViewmodel;
});

2
投票

angularjs的MVC模式意味着所有层(M,V,C)都在客户端。在这种模式中,服务器端通常会返回简单的json文件,这些文件是ajax在您使用MVC模式实现服务器端代码时所请求的。

因此,如果您更喜欢在服务器端代码上使用POJO,我建议将POJO转换为json格式并将其作为json文件提供。在客户端angularjs代码中,您可以将json转换为javascript简单对象并将其用作模型。


0
投票

你没有。你不能。

您可以使用Java创建Web服务。你可以make Angular to call that web service。但是你从Java到can't push data进入“Angular的模型”,因为那不是how the web works


0
投票

覆盖Car类的tostring方法

public String toString(){
        return new JSONObject(this).toString();
    }

你可以将该对象放在json中并将其作为json返回

Car car = new Car(1000, 4);

JSONObject jsonReturn = new JSONObject();
jsonReturn.put("car ", car );
© www.soinside.com 2019 - 2024. All rights reserved.