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

标签 javascript json angularjs angularjs-scope

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

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

我想要:

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

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

法比奥

最佳答案

On page load retrieve the json object from the service

一旦 Controller 加载,页面的 Controller 就可以调用服务来检索复杂对象。

Bind each property or nested object to the correct controller

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

如果您使用父子 Controller ,子 Controller 可以修改存储在父 Controller 作用域中的复杂对象。

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

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

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

Angular 的 2 路数据绑定(bind)将处理这部分。使用 ngModel 指令保存您需要的任何输入。您所做的任何更改都应该反射(reflect)在“主”对象中。

Send the modified object back to service for update and calcultation

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

您的 PageController 和服务可能如下所示:

页面 Controller

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

关于javascript - AngularJS 中与后端服务通信的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28065222/

相关文章:

json - 从 Typescript 解析 JSON 恢复数据成员但不是类型 : cannot call methods on result

javascript - angularjs ng-重复一长串无序列表

json - 在 Go 中,如何将 JSON 对象数组转换为具有默认值的结构数组?

javascript - 当小数为空时,Angular HTML 5 输入不显示任何内容

javascript - jQuery 使用 (new Function ("return "+ data))();而不是 eval(数据);解析JSON,为什么?

Javascript 局部变量声明

javascript - react 渲染数组以添加到列表中 - 简单的返回不起作用

javascript - 为什么无法在指令的 html 调用中访问 $rootScope?

javascript - AngularJS : ngRepeat in Directive with transcluded content

javascript - 根据客户端显示特定的 iframe