I'm tired of writing code

$scope.getTour = function () { $http({ url: "/tour/tour/" + $routeParams.id, method: "POST" }).success(function (data) { $scope.formData = data; }).error(function (data, status, headers, config) { $scope.status = status; }); }; $scope.onChangePublish = function (newValue, oldValue, tour_id) { $scope.published = newValue ? 1 : 0; $http({ url: "/tour/update-tour", method: "POST", data: { id: tour_id, published: $scope.published } }).success(function (data) { $scope.formData = data; }).error(function (data, status, headers, config) { $scope.status = status; }); }; 

I read that this is a bad tone, as it is necessary to make a request to the server in a separate service (factory) and continue to use one function. Tell me an example

  • Where did you read? What is the problem with the removal? - Grundy
  • I read it on a toaster, such as never using http services in controllers, but putting everything into separate services (factory). - ruslik
  • The problem is that I do not understand how to do it - ruslik
  • Help services - Grundy

1 answer 1

Yes it is a bad form.
Work with data should occur in services.
For example, here’s a service for adding an email subscription:

 (function () { 'use strict'; angular.module('common') .factory('newsletterService', newsletterService); function newsletterService($http, constants) { return { addNewsletter: addNewsletter }; function addNewsletter(email) { var data = angular.toJson({ email: email }); return $http.post(constants.restUrl + '/newsletter/register', data); } } })(); 

It is desirable to specify a reference to rest once in constants, to be used later in each service.

 (function () { 'use strict'; angular .module('common') .value('constants', { restUrl: 'http://rest.domain.ru }); }); 

The addNewsletter method of the newsletterService service returns $http.post , which accordingly returns promise . This promise must be subscribed to in the controller.

 (function () { 'use strict'; angular .module('common') .controller('newsletterCtrl', newsletterCtrl); function newsletterCtrl($scope, newsletterService) { $scope.addNewsletter = addNewsletter; function addNewsletter() { newsletterService.addNewsletter($scope.email).then(function(){ alert('Подписка прошла успешна'); }); } } }); 
  • found a more elegant option - resource - ruslik
  • @ruslik resourse is not always convenient - Namig