Angular js สร้างไฟล์ config เพื่อใช้งานอย่าง่าย : how to make easy config variable

ประโยชน์ของการมี  config endpoint พวกนี้คือเวลาที่มีการเปลี่ยน endpoint คือเปลี่ยนแค่ทีเดียว และมีผลกับทุกอย่างที่เรียกใช้ โดยเป็นหลัการทั่วไปของตัวแปร config Constant value วันนี้ผมจะมานำเสนอวิธีการสร้างตัวแปร config ของ angularjs และวิธีการใช้งานอย่างง่ายอีกรูปแบบหนึ่ง


  1. สร้างไฟล์ config ของ angular 
  2. /** config constant */
    (function() {
    var configModule = angular.module('configModule', []);
    configModule.constant('config', {
    local: {
    baseApi: 'http://localhost',
    port: '8080',
    register: '/register'
    timeOut: 1800,
    },
    staging: {
    baseApi: 'http://staging.acb',
    port: '8080',
    register: '/register'
    timeOut: 1800,
    },
    production: {
    baseApi: 'http://production.acb',
    port: '8080',
    register: '/register'
    timeOut: 1800,
    },
    });
    }());
    view raw configModule.js hosted with ❤ by GitHub
  3. ส่วนเรียกใช้งาน config ผ่านทาง controller
  4. /** use config app simple */
    (function() {
    var useConfigApp = angular.module('switchEnv', ['configModule']);
    useConfigApp.Controllers('simpleController', ['serviceEnv', function(serviceEnv) {
    var baseUrl = serviceEnv.env.baseApi;
    var port = serviceEnv.env.port;
    var register = serviceEnv.env.register;
    var timeOut = serviceEnv.env.timeOut;
    }]);
    }());
    view raw useConfigApp.js hosted with ❤ by GitHub
  5. ส่วนแยกแยะ env ของ config เพื่อ warp ข้อมูลให้ก่อนนำไปใช้งาน 
  6. /** switch env detect */
    (function() {
    var switchEnv = angular.module('switchEnv', ['useConfigApp']);
    switchEnv.service('serviceEnv', ['config','$location', function(config,$location) {
    this.env = function(host){
    var host = !angular.isUndefined(host) ? host : $location.host();
    switch(host) {
    case 'local':
    return config.local;
    break;
    case 'staging':
    return config.staging;
    break;
    case 'production':
    return config.production;
    break;
    default:
    return config.production;
    break;
    }
    }
    }]);
    }());
    view raw switchEnv.js hosted with ❤ by GitHub
Share on Google Plus

About maxcom

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 ความคิดเห็น:

แสดงความคิดเห็น