所以我开始研究一个自己的项目,我正在开发我的网站的前端.我开始使用
PHP Laravel后端,并为我的数据库设置了一个API服务.
考虑到混合应用程序,我开始在我的前端Web应用程序中使用angularjs.为了使用REST与我的API进行通信,我遇到了restangular,这非常好,因为它正是我所希望的.
只有一个困扰我的问题,没有真正的“指南”如何设置可维护的模块/工厂/提供者/服务来复制您的api系统将数据存储在本地存储或设置简单系统,您可以注入将“模型”转换为控制器,然后执行Model-> getAll()来获取所有模型.
因为我是angularJS的新手,因此我对如何解读这个问题的了解非常有限.到目前为止,我已经做到了这一点:
主要应用
var client = angular.module('clientApp',['angulartics','angulartics.google.analytics','ngRoute','restangular']); client.config(['$routeProvider',function($routeProvider){ $routeProvider .when('/',{ controller: 'flongsController',templateUrl: '/client_partials/Homepage.html' }) .when('/flongs/:slug',templateUrl: 'client_partials/Flong.html' }) .otherwise({ redirectTo: '/' }); }]);
flongsController
client.controller('flongsController',['$scope','Restangular','$routeParams',function ($scope,Restangular,$routeParams) { //controller variables var baseFlongs = Restangular.all('flongs'); $scope.flongs = {}; init(); function init() { baseFlongs.getList().then(function(flongs){ $scope.flongs = flongs; }); } }]);
所以,我的问题很简单:
如何改进此代码以使其更高效,更易于维护?
提前致谢,
Nick van der Meij
解决方法
首先,不要在控制器上使用服务逻辑,而是使用角度服务来实现此目的.
让我分享一下我如何构建我的项目,
首先构建Restangular服务:
angular.module('example').factory('exampleService',['Restangular',function(Restangular){ // this is service object with list of methods in it // this object will be used by controller var service = { getExamples: getExamples,getExample: getExample }; // get examples from server by using Restangular function getExamples(){ return Restangular.all('examples').getList(); } // get example with given id from server by using Restangular function getExample(exampleId){ return Restangular.one('examples',exampleId).get(); } return service; }]);
现在我们构建exampleService,让它将它注入控制器
angular.controller('ExampleCtrl',['exampleService',function(exampleService){ // get examples by using exampleService exampleService.getExamples().then(function (examples) { $scope.examples = examples; }); // get example with given id by using exampleService exampleService.getExample('1234').then(function (example) { $scope.example = example; }); }]);
这就是我基本上如何使用它.有关更高级的用法,请查看Restangular Github Page中的示例.