AngularJS - บริการ

AngularJS สนับสนุนแนวคิดเรื่องการแยกข้อกังวลโดยใช้สถาปัตยกรรมบริการ Services เป็นฟังก์ชัน JavaScript ซึ่งมีหน้าที่ดำเนินการเฉพาะงาน สิ่งนี้ทำให้แต่ละเอนทิตีซึ่งสามารถบำรุงรักษาและทดสอบได้ ตัวควบคุมและตัวกรองสามารถเรียกใช้ตามความต้องการ โดยปกติบริการจะฉีดโดยใช้กลไกการฉีดแบบพึ่งพาของ AngularJS

AngularJS ให้บริการ inbuilt มากมาย ตัวอย่างเช่น $ http, $ route, $ window, $ location เป็นต้นแต่ละบริการมีหน้าที่รับผิดชอบงานเฉพาะเช่น $ http ใช้ในการโทร ajax เพื่อรับข้อมูลเซิร์ฟเวอร์, $ route ใช้เพื่อกำหนด ข้อมูลเส้นทางและอื่น ๆ บริการ inbuilt จะขึ้นต้นด้วยสัญลักษณ์ $ เสมอ

มีสองวิธีในการสร้างบริการ -

  • Factory
  • Service

ใช้วิธีโรงงาน

ในวิธีนี้เรากำหนดโรงงานก่อนแล้วจึงกำหนดวิธีการให้

var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
   var factory = {};
   
   factory.multiply = function(a, b) {
      return a * b
   }
   
   return factory;
});

ใช้วิธีการบริการ

ในวิธีนี้เรากำหนดบริการจากนั้นกำหนดวิธีการให้ นอกจากนี้เรายังอัดฉีดบริการที่มีอยู่แล้วให้

mainApp.service('CalcService', function(MathService) {
   this.square = function(a) {
      return MathService.multiply(a,a);
   }
});

ตัวอย่าง

ตัวอย่างต่อไปนี้แสดงการใช้คำสั่งที่กล่าวถึงข้างต้นทั้งหมด -

testAngularJS.htm

<html>
   <head>
      <title>Angular JS Services</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
   </head>
   
   <body>
      <h2>AngularJS Sample Application</h2>
      
      <div ng-app = "mainApp" ng-controller = "CalcController">
         <p>Enter a number: <input type = "number" ng-model = "number" /></p>
         <button ng-click = "square()">X<sup>2</sup></button>
         <p>Result: {{result}}</p>
      </div>
      
      <script>
         var mainApp = angular.module("mainApp", []);
         
         mainApp.factory('MathService', function() {
            var factory = {};
            
            factory.multiply = function(a, b) {
               return a * b
            }
            return factory;
         });
         mainApp.service('CalcService', function(MathService) {
            this.square = function(a) {
               return MathService.multiply(a,a);
            }
         });
         mainApp.controller('CalcController', function($scope, CalcService) {
            $scope.square = function() {
               $scope.result = CalcService.square($scope.number);
            }
         });
      </script>
      
   </body>
</html>

เอาต์พุต

เปิดไฟล์testAngularJS.htmในเว็บเบราว์เซอร์และดูผลลัพธ์