如何与AngularJS中的后端服务进行通信的最佳方法

问题描述 投票:0回答:2

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

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

我想要:

  • 页面加载时,从服务中检索json对象
  • 将每个属性或嵌套对象绑定到正确的控制器
  • 用户通过UI修改值
  • 收集所有修改后的数据并重建复杂对象
  • 将修改后的对象发送回服务以进行更新和计算

以前,我使用Knockout.js并轻松完成此任务,从而序列化模型和使用映射插件。 AngularJS中最好的方法是什么? 提前致谢。

法比奥

javascript json angularjs angularjs-scope
2个回答
2
投票

页面加载时,从服务中检索json对象

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

将每个属性或嵌套对象绑定到正确的控制器

有很多方法可以做到这一点。 一旦有了对象,就可以直接引用其属性并将其传递给其他对象。

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

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

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

用户通过UI修改值
收集所有修改后的数据并重建复杂对象

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

将修改后的对象发送回服务以进行更新和计算

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

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

页面控制器

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]);

0
投票

尝试使用此方法来获取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
});

并尝试将其发布回服务器:

// 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教程

和/或遵循Angular API参考

希望对您有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.