AngularJS 中与后端服务通信的最佳方法是什么

How is the best approach to communicate with backend service in AngularJS

我是 AngularJS 的初学者。我想知道哪种方法是解决我的问题的最佳方法。我有一个服务 return 一个像这样的复杂 JSON 对象(更复杂!!!):

var complexObj = {
    property1: 'p1',
    property2: 'p2',
    complexNested: {
        nestedProperty1: 'np1',
        nestedProperty2: 'np2'
    },
    arrayOfObjects: [{ arrP1: 'arrp1', arrP2: 'arrp2' }, { arrP1:'arrp3', arrP2: 'arrp4' }]
};

我要:

之前我使用 Knockout.js 轻松完成了这个任务序列化模型和使用映射插件。 AngularJS 中哪种方法最好? 提前致谢。

法比奥

尝试用这个得到 json:

// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
  // Parse jour json
}).
error(function(data, status, headers, config) {
  // show errors
});

并尝试使用此 post 返回服务器:

// Simple POST request example (passing data) :
var json = {one:"one", two:"two"};
$http.post('/someUrl', json).
success(function(data, status, headers, config) {
  // this callback will be called asynchronously
}).
error(function(data, status, headers, config) {
  // called asynchronously if an error occurs
});

如果你想要一个好的入门指南,请按照 angualJS 的 codeplex 教程的第 5 课第 2 节进行操作:AngulaJS tutorial

and/or 关注 Angular API reference

希望对您有所帮助!

On page load retrieve the json object from the service

您页面的控制器可以在控制器加载后立即调用服务来检索复杂对象。

Bind each property or nested object to the correct controller

有很多方法可以做到这一点。拥有对象后,您可以直接引用其属性并传递它的各个部分。

如果您使用的是父子控制器,则子控制器可以修改存储在父范围内的复杂对象。

如果您使用指令,则可以根据需要通过隔离范围传递复杂对象的特定部分。

您还可以将复杂对象存储在服务中(这是一个单例)并在控制器之间共享。

User modify the values through UI
Collect all the modified data and rebuild the complex object

Angular 的 2 向数据绑定将处理这部分。使用 ngModel 指令保存您需要的任何输入。您所做的任何更改都应反映在 'master' 对象中。

Send the modified object back to service for update and calcultation

这将是再次调用您的服务的问题,它应该以该对象作为其主体发出 PUT 请求。

您的 PageController 和服务可能看起来像这样:

页面控制器

function PageController($scope, ComplexObjectService) {
    loadComplexObject();
    function loadComplexObject() {
        ComplexObjectService.get().then(function(complexObject) {
            $scope.complexObject = complexObject;
        });
    }

    $scope.onSave = function(complexObject) {
        ComplexObjectService.save(complexObject).then(function(result) {
            //Do something.
        });
    }


}
angular
    .module('ModuleName')
    .controller('PageController', ['$scope', 'ComplexObjectService', PageController]);

复杂服务

function ComplexObjectService($http) {
    this.get = function() {
        return $http.get('/api/to/get/complex/object').then(function(response) {
            return response.data;
        });
    };

    this.save = function(complexObject) {
        return $http.put('/api/to/save/complex/object', complexObject).then(function(response) {
            return response.data;
        });
    };
}
angular
    .module('ModuleName')
    .service('ComplexObjectService', ['$http', ComplexObjectService]);