简体   繁体   English

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

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

I am a beginner with AngularJS. 我是AngularJS的初学者。 I want to know which is the best approach for solve my problem. 我想知道哪种是解决我的问题的最佳方法。 I have a service which return a complex JSON object like this (more complex!!!): 我有一个服务,它返回像这样的复杂JSON对象(更复杂!!!):

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

I want: 我想要:

  • On page load retrieve the json object from the service 页面加载时,从服务中检索json对象
  • Bind each property or nested object to the correct controller 将每个属性或嵌套对象绑定到正确的控制器
  • User modify the values through UI 用户通过UI修改值
  • Collect all the modified data and rebuild the complex object 收集所有修改后的数据并重建复杂对象
  • Send the modified object back to service for update and calcultation 将修改后的对象发送回服务以进行更新和计算

Previously I used Knockout.js and complete this task easily serializing the model and using the mapping plugin. 以前,我使用Knockout.js并轻松完成此任务,从而序列化模型和使用映射插件。 Which is the best way in AngularJS? AngularJS中最好的方法是什么? Thanks in advance. 提前致谢。

Fabio 法比奥

On page load retrieve the json object from the service 页面加载时,从服务中检索json对象

The Controller for your page can call the Service to retrieve the complex object as soon as the controller loads. 页面的控制器可以在控制器加载后立即调用服务以检索复杂对象。

Bind each property or nested object to the correct controller 将每个属性或嵌套对象绑定到正确的控制器

There's many ways to do this. 有很多方法可以做到这一点。 Once you have your object, you can reference its properties directly and pass pieces of it around. 一旦有了对象,就可以直接引用其属性并将其传递给其他对象。

If you're using parent-child controllers, the child can modify the complex object that is stored in the parent's scope. 如果您使用的是父子控制器,则子可以修改存储在父范围内的复杂对象。

If you use directives, you can pass specific pieces of the complex object as needed via isolated scopes. 如果使用指令,则可以通过隔离的作用域根据需要传递复杂对象的特定部分。

You can also have the complex object stored in the Service (which is a singleton) and shared between controllers. 您还可以将复杂对象存储在服务中(单例),并在控制器之间共享。

User modify the values through UI 用户通过UI修改值
Collect all the modified data and rebuild the complex object 收集所有修改后的数据并重建复杂对象

Angular's 2-way data-binding will handle this part. Angular的2向数据绑定将处理此部分。 Use the ngModel directive to save whatever input you need. 使用ngModel指令保存您需要的任何输入。 Any changes you make should be reflected back in the 'master' object. 您所做的任何更改都应反映在“主”对象中。

Send the modified object back to service for update and calcultation 将修改后的对象发送回服务以进行更新和计算

This would be a matter of calling your Service again, which should make a PUT request with the object as its body. 这将是再次调用服务的问题,该服务应以该对象为主体来发出PUT请求。

Your PageController and Service might look something like this: 您的PageController和Service可能看起来像这样:

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

ComplexService 综合服务

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

Try with this to get the json: 尝试使用此方法来获取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
});

And try with this to post back to the server: 并尝试将其发布回服务器:

// 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
});

If you want a good getting started guide follow the lesson number 5 section 2 on the codeplex tutorial on angualJS: AngulaJS tutorial 如果您想获得良好的入门指南,请遵循angualJS的codeplex教程上的第5课第2节: AngulaJS教程

and/or follow the Angular API reference 和/或遵循Angular API参考

Hope this help! 希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM