hocvietcode.com
  • Trang chủ
  • Học lập trình
    • Lập trình C/C++
    • Lập trình HTML
    • Lập trình Javascript
      • Javascript cơ bản
      • ReactJS framework
      • AngularJS framework
      • Typescript cơ bản
      • Angular
    • Lập trình Mobile
      • Lập Trình Dart Cơ Bản
        • Dart Flutter Framework
    • Cơ sở dữ liệu
      • MySQL – MariaDB
      • Micrsoft SQL Server
      • Extensible Markup Language (XML)
      • JSON
    • Lập trình PHP
      • Lập trình PHP cơ bản
      • Laravel Framework
    • Lập trình Java
      • Java Cơ bản
    • Cấu trúc dữ liệu và giải thuật
    • Lập Trình C# Cơ Bản
    • Machine Learning
  • WORDPRESS
    • WordPress cơ bản
    • WordPress nâng cao
    • Chia sẻ WordPress
  • Kiến thức hệ thống
    • Microsoft Azure
    • Docker
    • Linux
  • Chia sẻ IT
    • Tin học văn phòng
      • Microsoft Word
      • Microsoft Excel
    • Marketing
      • Google Adwords
      • Facebook Ads
      • Kiến thức khác
    • Chia sẻ phần mềm
    • Review công nghệ
    • Công cụ – tiện ích
      • Kiểm tra bàn phím online
      • Kiểm tra webcam online
Đăng nhập
  • Đăng nhập / Đăng ký

Please enter key search to display results.

Home
  • AngularJS
Factory và Service trong angularJS

Factory và Service trong angularJS

  • 29-04-2022
  • Toanngo92
  • 0 Comments

Ngooài việc sử dụng provider để tạo các service, AngularJS triển khai các ý tưởng thông qua kiến trúc nghiệp vụ (services). AngularJs cung cấp 2 hàm để tạo service là:

  • factory()
  • service()

Mục lục

  • Factory
  • Service
    • Sự khác biệt giữa Service và Factory

Factory

Factory là một phương thức trả về giá trị, có thể sử dụng lại để thực thi các tác vụ như là validate, hay quy tắc các nghiệp vụ, factory tạo ra các giá trị mong muốn khi controller hoặc service cần nó. Những giá trị được tạo này có thể sử dụng lại cho contrrollers hoặc services bất cứ khi nào cần

Phương thức factory() là một hàm, nó tạo ra một đối tượng factory và return đối tượng đó, vì vậy nó không giống với giá trị tạo ra từ phương thức value() mình mô tả phía trên, factory sử dụng function giúp làm các nghiệp vụ phức tạp hơn như tính toán giá trị … xây dựng logic return giá trị, sau đó return giá trị về và có thể tiêm tương tự như phương thức value()

Ví dụ về factory

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example Factory</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.js"></script>
    <style>
        input,
        select {
            margin-bottom: 10px;
        }
    </style>
</head>

<body ng-app="myApp">
    <div ng-controller="myCtrl">
        <h1>Calculate total product</h1>
        Product price:
        <br />
        <input type="number" ng-model="price" />
        <br />
        Shipping type:
        <br />
        <select ng-model="shippingtype">
            <option value="flat">Flat shipping - 10$</option>
            <option value="custom">Express - custom price</option>
        </select>
        <br />
        <input type="number" ng-model="shipping" ng-show="shippingtype == 'custom'" />
        <br />
        <p>Total: {{calculate()}}</p>
    </div>
</body>
<script>
    var myApp = angular.module('myApp', []);
    myApp.factory("calculateOrderService", function () {
        //define factory varialble
        var factory = {};
        factory.flatShipping = function (price) {
            // shipping price value is 10
            return price + 10;
        }
        factory.customShipping = function (price, shipping) {
            // shipping price value is 20
            return price + shipping;
        }
        return factory;
    });
    myApp.controller("myCtrl", function ($scope, calculateOrderService) {
        $scope.price = 0;
        $scope.shipping = 0;
        $scope.total = 0;
        $scope.shippingtype = "flat";
        $scope.calculate = function () {
            if ($scope.shippingtype == "flat") {
                $scope.total = calculateOrderService.flatShipping($scope.price);
            } else {
                $scope.total = calculateOrderService.customShipping($scope.price, $scope.shipping);
            }
            return $scope.total;
        };
    });
</script>

</html>

Service

Trong angularJS, service tham chiếu tới một đối tượng singleton, lưu trữ một tập hợp các hàm có thể tiêm vào controoller, những hàm này có logic để giúp service có thể xử lý công việc,ví dụ service $http sử dụng để tiêm vào controller để làm các nghiệp vụ về HTTP

Để tạo ra một service trong module,AngularJS cung cấp phương thức service(), với phương thức này, chúng ta định nghĩa service và gán các phương thức mong muốn vào nó, Một service có hàm constructor ( khởi tạo), sử dụng từ khóa new để tạo ra đối tượng và đưa các phương thức, thuộc tính vào trong nó. Tuy nhiên, không giống factory, bên trong service sau khi định nghĩa không return giá trị, mọi thứ được đưa vào service thông qua this (ngữ cảnh chính đối tượng đó). Một service có thể được tiêm vào các service khác, filter, controller, directive …

Ví dụ khởi tạo dữ liệu thông qua service:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example Service</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"></script>
</head>

<body ng-app="myApp">
    <div ng-controller="myController">
        <select ng-model="selectedlistOption" ng-change="alertselected()" ng-options="item as item.name for item in listOption track by item.id">
        </select>
    </div>
</body>
<script>
    var app = angular.module('myApp', []);
    app.service('myService', function () {
        this.optionDefault = {id: 0, name: "Choose nothing"};
        this.addListOption = function (listOption) {
            listOption.unshift(this.optionDefault);
        };
    });
    app.controller('myController', function ($scope, myService) {
   //     $scope.selected = "";
        $scope.listOption = [
            {id: 1, name: "Option 1"},
            {id: 2, name: "Option 2"},
            {id: 3, name: "Option 3"},
            {id: 4, name: "Option 4"},
        ];
        myService.addListOption($scope.listOption);
        $scope.selectedlistOption= $scope.listOption[0];
        $scope.alertselected = function(){    
            console.log($scope.selectedlistOption);
        }
    });
</script>

</html>

Với ví dụ trên, mình làm công việc sử dụng service thông qua cơ chế tiêm, đưa một option mặc định select vào trong danh sách select vừa khởi tạo và chọn nó làm selected mặc định.

Sự khác biệt giữa Service và Factory

Sự khác biệtFactoryService
Kiểu funtion (function type)Là một hàm, trả về đối tượng hoặc giá trịLà một hàm khởi tạo (constructor function), hoặc khởi tạo thông qua từ khóa new
Sử dụng (Use)Sử dụng cho service không cấu hình, thường hay sử dụng trong cấu trúc logic phức tạpPhù hợp sử dụng trong cấu trúc logic đơn giản
Đặc tính (Property)định nghĩa không sử dụng từ khóa thisSử dụng từ khóa this
Cơ chế tiêm thân thiện (Friendly Injection)Không hỗ trợHỗ trợ
Primitives (nguyên thủy)CóKhông
Lựa chọn ưu tiên (Preferable choice)Ưu tiên khi định nghĩa classƯu tiên khi định nghĩa ra các tiện ích nhanh chóng, hoặc định nghĩa hàm chuẩn ES6

Bài viết liên quan:

Cơ chế dependency Injection (cơ chế tiêm phụ thuộc) trong angularJS
Animation trong angularJS
Form validation trong angularJS
Route (định tuyến) trong angularJS
Filter (bộ lọc) trong angularJS
Service trong AngularJS và các service giao tiếp với máy chủ
Scope và rootScope trong AngularJS
Directive (chỉ thị) trong angularJS và danh sách các directive
Event handling (xử lý xự kiện) trong angularJS
Cơ chế Data binding trong AngularJS
Expressions (biểu thức) trong AngularJS
Views trong AngularJS

THÊM BÌNH LUẬN Cancel reply

Dịch vụ thiết kế Wesbite

NỘI DUNG MỚI CẬP NHẬT

4. KIỂM THỬ VÀ TRIỂN KHAI HỆ THỐNG

2. PHÂN TÍCH VÀ ĐẶC TẢ HỆ THỐNG

5. VIẾT BÁO CÁO VÀ THUYẾT TRÌNH DỰ ÁN

3. THIẾT KẾ HỆ THỐNG

1. TỔNG QUAN KIẾN THỨC THỰC HÀNH TRIỂN KHAI DỰ ÁN CÔNG NGHỆ THÔNG TIN

Giới thiệu

hocvietcode.com là website chia sẻ và cập nhật tin tức công nghệ, chia sẻ kiến thức, kỹ năng. Chúng tôi rất cảm ơn và mong muốn nhận được nhiều phản hồi để có thể phục vụ quý bạn đọc tốt hơn !

Liên hệ quảng cáo: [email protected]

Kết nối với HỌC VIẾT CODE

© hocvietcode.com - Tech888 Co .Ltd since 2019

Đăng nhập

Trở thành một phần của cộng đồng của chúng tôi!
Registration complete. Please check your email.
Đăng nhập bằng google
Đăng kýBạn quên mật khẩu?

Create an account

Welcome! Register for an account
The user name or email address is not correct.
Registration confirmation will be emailed to you.
Log in Lost your password?

Reset password

Recover your password
Password reset email has been sent.
The email could not be sent. Possible reason: your host may have disabled the mail function.
A password will be e-mailed to you.
Log in Register
×