简体   繁体   中英

In Angular (PhoneGap), what's the best way to structure an AJAX call and use the return as storable JSON data?

I am just getting started with Angular, and do not have a programming background (I'm a designer, uh-oh). I'm mixing together two PhoneGap starter projects, picking apart their code to fit my idea. I'm trying to reverse-engineer a very simple master-detail app that uses some JSON, and change this so it fetches the data via AJAX . Eventually I would like to store the data in the app once intially fetched, and get it to update any new data from the AJAX source.

At the moment the app has:

module.factory('$data', function() {
    var data = {};
    data.items = [
        {
            title: 'A bunch of data',

..etc..

Outside of this (in fact before it), I have written my AJAX call:

module.controller('AppController', ['$scope','$http', function($scope,$http) {
    $http({
        method: 'GET',
        url: 'http://www.my-web-adddress.net/api/blah'
    }).then(function successCallback(response) {
        var results = response["data"];
        for( var i = 0, len = results.length; i < len; i++ ){...

..Where I can then manipulate the data. However I am unsure about passing the data between these two functions, or whether I am best trying to write a single function. If it should be a single function, I am struggling with the factory vs service vs controller conventions, scope, injection, etc, so if someone could give me a quick example about how they would structure it that would be amazing.

As a rule of thumb, it is good practice to place all CRUD operations (Create, Read, Update and Delete) in a separate factory/service. This allows for easier testing and re-usability.

module.factory('MyDataFactory', ['$http',
  {
    return {
      getData: function(){
        return $http.get('http://www.my-web-adddress.net/api/blah')
      }

      // My other CRUD operations

    };
  }]);

This is returned as a promise which can now be called from you controller:

module.controller('AppController', ['$scope','MyDataFactory',
  function($scope, MyDataFactory) {
    MyDataFactory.getData().then(function successCallback(response){
      var results = response["data"];
    },  
    function errorCallback(response){
      console.log(response);
    }
}])

You might also want to look into caching , which is really easy using $http .
When it comes to the whole factory vs service vs ... this thread is a good read

Note that the above code has not been tested, it should provide you with an outline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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