AngularJS: Creating Objects that map to REST Resources (ORM-Style)

前端 未结 7 659
南笙
南笙 2021-01-29 18:09

I\'m pretty new to AngularJS, but I\'m pretty unclear on how to tie it up to my Server\'s REST Api backend.

For example, say I have an \"image\" resource that I get by G

7条回答
  •  执笔经年
    2021-01-29 18:40

    ModelCore ( https://github.com/klederson/ModelCore ) works pretty much like this, and is very very easy to implement:

    var ExampleApp = angular.module('ExampleApp', ['ModelCore']); //injecting ModelCore
    
    ExampleApp.factory("Users",function(ModelCore) {
      return ModelCore.instance({
        $type : "Users", //Define the Object type
        $pkField : "idUser", //Define the Object primary key
        $settings : {
          urls : {
            base : "http://myapi.com/users/:idUser",
          }
        },
        $myCustomMethod : function(info) { //yes you can create and apply your own custom methods
            console.log(info);
        }
      });
    });
    
    //Controller
    function MainCrtl($scope, Users) {
      //Setup a model to example a $find() call
      $scope.AllUsers = new Users();
    
      //Get All Users from the API
      $scope.AllUsers.$find();
    
      //Setup a model to example a $get(id) call
      $scope.OneUser = new Users();
    
      //Hey look there are promisses =)
      //Get the user with idUser 1 - look at $pkField
      $scope.OneUser.$get(1).success(function() {
        console.log("Done!",$scope.OneUser.$fetch());
    });
    

提交回复
热议问题