简体   繁体   中英

Services in Angular

I'm quite new with Angular and I am trying to bring some structure in my website I am building with Angular.

Now I have a Controller where I have some functions which I use on multiple pages. I have heard that I could better make a service out of these functions. How am I able to do this?

This is my Controller in current state: How can I make a service from $scope.city function and $scope.specials function?

app.controller('DataCtrl', function($scope,$http){
  $scope.city = function(){
    $scope.items = [];

    $http.get('/getdata').then(function(d){
      $scope.items = d.data;
      $scope.selectedItem = $scope.items[0];
    },function(err){
      console.log(err);
    });
  };

  /* Function for specialization data */
  $scope.specials = function(){
    $scope.special = [];

    $http.get('/specialdata').then(function(d){
      $scope.special = d.data[0];
    },function(err){
      console.log(err);
    });
  };
});

Define a service , Here is an example

//Service.js
(function () {
    angular.module('myApp')
    .service('myService', service);

    service.$inject = ['$http']
    function service($http) {
        this.specialdata = function () {
            return $http.get('/specialdata')
        }
    }
})();

//Controller.js
(function () {
    angular.module('myApp')
    .controller('DataCtrl', DataCtrl);

    DataCtrl.$inject = ['$scope', 'myService']
    function DataCtrl($scope, myService) {
        /* Function for specialization data */
        $scope.specials = function () {
            $scope.special = [];

            myService.specialdata().then(function (d) {
                $scope.special = d.data[0];
            }, function (err) {
                console.log(err);
            });
        };
    }
})();

Try like this

 app.factory('getServiceData', function($http){
 return {
    getSpecials: function() {
      return $http.get("/specialdata")
     }
   };
});

and for use it in controller inject factory or service into controller as you see in bellow.

 app.controller('DataCtrl', function($scope,getServiceData){
 getServiceData.getSpecials().then(function(response){
        $scope.special =  response.data[0];
    })
  };

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