Advertisement
  1. Code
  2. JavaScript
  3. Angular

สร้าง Web App จากความว่างเปล่าโดยใช้ AngularJS และ Firebase

Scroll to top
Read Time: 6 min
This post is part of a series called Creating a Web App From Scratch Using AngularJS and Firebase.
Creating a Web App From Scratch Using AngularJS and Firebase: Part 2

() translation by (you can also view the original English article)

ในซีรีย์นี้ เราจะใช้ AngularJS และ Firebase เพื่อทำการสร้างเว็บ แอปพลิเคชันแบบง่ายๆ จากความว่างเปล่ากันเลย มันจะเป็นแอพพลิเคชันระบบ blog แบบเรียบง่ายที่สุด ที่ผู้ใช้งานสามารถ sign in หรือ sign up เพื่อเผยแพร่บทความบน blog ของพวกเขาได้

บทเรียนนี้จะสมมุติว่าคุณมีพื้นฐานการเขียน AngularJS มาบ้างแล้ว แต่มันไม่จำเป็นเท่าไหร่ เพราะเราจะกล่าวถึงเรื่องที่ต้องใช้ระหว่างบทเรียนไปทีละอัน

แนะนำ AngularJS

AngularJS นั้นเป็นหนึ่งใน JavaScript MVC Framework ยอดนิยมตัวหนึ่ง โครงสร้าง Framework ของมันมีไว้สำหรับสร้าง Dynamic Web Application ด้วยขยายความสามารถที่มีอยู่ของ HTML มันมีฟีเจอร์ที่สำคัญเช่น Data Binding และ Dependency Injection ทำให้มันง่ายที่จะสร้าง App ที่ใช้โค้ดจำนวนน้อย

ข้อความจาก AngularJS documentation

HTML นั้นยอดเยี่ยมสำหรับเอกสารที่เนื้อหาไม่เปลี่ยนแปลง (static document) แต่มันใช้ไม่ได้เมื่อเราพยายามใช้มันสำหรับส่วนของเนื้อหาที่เปลี่ยนแปลงได้ (Dynamic View) ในเว็บแอปพลิเคชันของเรา AngularJS นั้นช่วยให้เราขยายคำสั่ง HTML เพื่อใช้สำหรับเขียน Application ได้ ผลลัพธ์นั้นค่อนข้างเยี่ยมยอด อ่านได้ง่ายและสามารถพัฒนาได้อย่างรวดเร็ว

แนะนำ Firebase

จินตนาการว่าเราสร้าง Web Application โดยไม่ต้องกังวลเกี่ยวกับส่วนของ Back-end  Firebase นั้นทำได้ในการ sync data แบบ real time กับแอปพลิเคชันของเรา โดยไม่ต้องไปกังวลหรือเขียนโค้ด back-end เลย ทั้งหมดที่เราต้องทำคือเขียนสิ่งที่เรียกว่า API calls

Firebase นั้นมี API ที่ทรงพลังที่จะเก็บข้อมูลและ sync แบบ real time การรวมพลังของ AngularJS เรื่อง two-way data binding กับ Firebase ให้ผลลัพธ์ในรูปแบบ three-way synchronization ซึ่งมันค่อนข้างเยี่ยมยอด

เริ่มต้นกับ AngularJS

ชุดโปรเจค angular-seed นั้นเป็นแม่แบบเพื่อให้เริ่มต้นสร้าง web apps โดยใช้ AngularJS ได้ โปรดทำการ Download หรือ clone โปรเจค angular-seed จาก repository นี้

1
$ git clone https://github.com/angular/angular-seed.git

เพียงแค่ไปที project directory และ install required dependencies

1
$ cd angular-seed

2
$ npm install             ## Install the dependencies

ทำการ Start node server

1
$ npm start               ## Start the server

ชี้เบราว์เซอร์ของคุณไปที่ https://localhost:8000/app/index.html และคุณควรเห็นว่า app แบบดีฟอลต์นั้นเริ่มทำงาน

ไปที่ app ไดเร็กเทอรี่ภายใต้ angular-seed นี่คือที่ที่ๆ โค้ดของแอปพลิเคชันนั้นวางอยู่ ภายใต้ app folder คุณจะสามารถพบไฟล์ app.js ที่ซึ่งเป็นไฟล์หลักของ app เราจะประกาศ app-level module ทั้งหมดและ route ภายใต้ไฟล์นี้ โดยค่าดีฟอลต์ของโปรเจค angular-seed นั้นมี view 2 อัน คือ view1 และ view2 เราจะลบโฟลเดอร์ view1 และ view2 ออกจากโฟลเดอร์ app

เริ่มจากไม่มีอะไรเลย เปิดไฟล์ app.js และเอาโค้ดที่มีอยู่ออก ในไฟล์ app.js เราจะประกาศแอปพลิเคชัน route ยกตัวอย่าง การจัดการกับ request เช่น /home ในทางที่ประกาศ route เราต้องการ AngularJS โมดูลที่เรียกว่า ngRoute เพื่อที่จะใช้ ngRoute อย่างแรกเราต้อง inject มันหรือเพิ่มมันไปที่แอปพลิเคชันของเรา เราจะใช้ angular.module เพื่อเพิ่ม ngRoute โมดูลไปที่ app ที่แสดงไว้ตามข้างล่างนี้

1
angular.module('myApp', [
2
  'ngRoute'
3
])

โมดูล ngRoute นั้นมีคอมโพเน้นท์ที่ชื่อว่า $routeProvider ที่ซึ่งมีประโยชน์มากในการ config route เราจะ inject $routeProvider ไปใน config method ของ angular.module และประกาศ route ในฟังก์ชัน callback ของมัน ดังที่แสดงไว้ด้านล่างนี้

1
'use strict';
2
3
angular.module('myApp', [
4
  'ngRoute'
5
]).
6
config(['$routeProvider', function($routeProvider) {
7
     // Routes will be here

8
}]);

ถัดไป ให้เปิดไฟล์ index.html และเอา script reference ที่ view1 และ view2 ออก เอาทุกอย่างจาก body ของ index.html ออกให้หมดยกเว้น script reference และ div ที่แสดงภายใต้ ngView directive

1
<div ng-view></div>

ngView นั้นเป็น directive ที่ซึ่งช่วยให้เรา render ส่วนของ view ที่ติดตั้ง route นั้นๆ เข้าไปยัง main layout หรือไฟล์ index.html ดังนั้นแต่ละเวลาที่ route เกิดการเปลี่ยนแปลง เนื้อหาภายใน div จะสามารถแสดงการเปลี่ยนแปลงได้

จากนี้เรามาสร้าง view ใหม่สำหรับผู้ใช้งาน sign in กัน ภายใต้ app directory สร้างโฟลเดอร์ใหม่ที่ชื่อว่า home ภายใน home สร้างไฟล์สองไฟล์ที่เรียกว่า home.html และ home.js เปิดไฟล์ home.html และใส่ HTML code เหล่านี้ลงไป

1
<!DOCTYPE html>
2
<html lang="en" ng-app="myApp">
3
4
<head>
5
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6
    <link rel="icon" href="http://getbootstrap.com/favicon.ico">
7
8
    <title>AngularJS & Firebase Web App</title>
9
10
    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
11
    <link href="http://getbootstrap.com/examples/signin/signin.css" rel="stylesheet">
12
13
    <link href="justified-nav.css" rel="stylesheet">
14
15
</head>
16
17
<body>
18
19
    <div class="container">
20
        <div class="jumbotron" style="padding-bottom:0px;">
21
            <h2>AngularJS & Firebase App!</h2>
22
        </div>
23
        <form class="form-signin" role="form">
24
            <input type="email" class="form-control" placeholder="Email address" required="" autofocus="">
25
            <input type="password" class="form-control" placeholder="Password" required="">
26
            <label class="checkbox">
27
                <a href="#"> Sign Up</>
28
        </label>
29
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
30
      </form>
31
32
    </div>
33
34
  
35
36
</body></html>

อย่างที่เห็นตามโค้ดด้านบน เราจะใช้ Bootstrap เพื่อสร้าง application view ของเรา

ภายใน home.js เราจะประกาศ route สำหรับ application เพื่อให้เข้าถึง home view $routeProvider นั้นมี method ที่ถูกเรียกว่า when ที่ซึ่งเราจะใช้เพื่อสร้าง route สำหรับ home view ของเรา และเมื่อประกาศ route ใหม่ เราจะตั้งค่า templateUrl ที่ซึ่ง render ภายใต้ index.html ไปกับสิ่งเหล่านั้น เราจะตั้งค่า controller สำหรับ $scope ที่สร้างขึ้นใหม่ใน home view ของเรา controller นั้นคือ logic ที่ผูกกับ control view อันใดอันหนึ่ง นี่แหละที่มันจะออกมา

1
'use strict';
2
3
angular.module('myApp.home', ['ngRoute'])
4
5
// Declared route 

6
.config(['$routeProvider', function($routeProvider) {
7
    $routeProvider.when('/home', {
8
        templateUrl: 'home/home.html',
9
        controller: 'HomeCtrl'
10
    });
11
}])
12
13
// Home controller

14
.controller('HomeCtrl', [function() {
15
16
}]);

จากนั้น เปิดไฟล์ app.js และเอาโมดุล home ใส่ไว้ใน myApp.home ในแอพด้วย และก็ประกาศ default route สำหรับแอพพลิเคชันของเราโดยใช้ $routeProvider.otherwise method ที่ home view

1
'use strict';
2
3
angular.module('myApp', [
4
    'ngRoute',
5
    'myApp.home'           // Newly added home module

6
]).
7
config(['$routeProvider', function($routeProvider) {
8
    // Set defualt view of our app to home

9
    
10
    $routeProvider.otherwise({
11
        redirectTo: '/home'
12
    });
13
}]);

ถัดไป ในการที่จะแสดงหน้า homepage เราจะเพิ่ม home.js ภายในไฟล์ main HTML template ของ app เปิดไฟล์ index.html และใส่สิ่งต่างๆ ต่อไปนี้

1
<script src="home/home.js"></script>

ทำการรีสตาร์ท server และสั่งเบราว์เซอร์ไปที่ http://localhost:8000/app/index.html และคุณควรจะเห็นปุ่ม sign-in บนหน้าจอ

AngularJS FirebaseAngularJS FirebaseAngularJS Firebase

เริ่มต้นกับ Firebase

ในฐานะที่เริ่มต้น เราต้องลงทะเบียนเพื่อให้ได้ Account ฟรีบน Firebase เสียก่อน เมื่อลงทะเบียนสำเร็จแล้ว เราจะได้หน้าจอเหมือนแบบนี้

Firebase DashboardFirebase DashboardFirebase Dashboard

โปรดบันทึกไว้ว่า URL ของ app คุณนั้นถูกสร้างและคลิกลงบนปุ่ม Manage App  ทีนี้เราจะสามารถใช้ Firebase URL เพื่อที่จะจัดการกับ Firebase database ได้แล้ว

เราจะทำการใช้ Firebase เพื่อยืนยันตัวตน (Authenticate) แอปพลิเคชันของเราโดยการใช้ E-mail และ password เพื่อที่จะทำให้มันทำงานได้จริงๆ เราต้อง Enable มันจาก Firebase จาก dashboard ให้คลิกบน Login & Auth tab ใน left-side menu ใน screen นั้น ภายใต้ Email & Password tab ลอง check Enable Email & Password Authentication ที่แสดงไว้ดังรูปดู

Enable Email Password AuthenticationEnable Email Password AuthenticationEnable Email Password Authentication

เพิ่ม user ใหม่ด้วย Email และ Password ที่ซึ่งเราจะ authenticate หลังจาก implementing ฟังก์ชัน sign-in เรียบร้อยแล้ว

Add a new user with an Email and PasswordAdd a new user with an Email and PasswordAdd a new user with an Email and Password

ทำการ Implement ฟังก์ชัน Sign-In

ในฐานะที่จะเริ่มใช้ Firebase เราต้องใส่สคริปต์เหล่านี้เข้าไป app/index.html

1
<script src="https://cdn.firebase.com/js/client/1.0.18/firebase.js"></script>
2
<script src="https://cdn.firebase.com/libs/angularfire/0.8.0/angularfire.min.js"></script>
3
<script src="https://cdn.firebase.com/js/simple-login/1.6.2/firebase-simple-login.js"></script>

ถัดไป เราจะ inject โมดูล firebase เข้าไปใน home.js และเพิ่มโมดูล firebase เข้าไปใน home.js ดังโค้ดด้านล่าง

1
angular.module('myApp.home', ['ngRoute','firebase'])

และแล้ว เราพร้อมแล้วที่จะเริ่มทำงานกับ Firebase เพิ่มไฟล์ home.js ไปที่ภายใต้ HomeCtrl ให้สร้างฟังก์ชันใหม่ที่ชื่อ SignIn เพื่อ authenticate user เราจะใช้ $scope เพื่อสร้างฟังก์ชันใหม่ ซึ่ง $scope นั้นคือ object ที่อ้างอิงไปถึง application model ของเราและมันทำงานเหมือนกาวที่เชื่อมระหว่าง application controller และ view  ดังนั้นเราจะ inject $scope object เข้าไปในฟังก์ชัน SignIn ดังนั้น object model จาก view นั้นจะสามารถเข้าถึงได้ภายใต้ฟังก์ชัน SignIn นั้น

1
$scope.SignIn = function($scope) {
2
    var username = $scope.user.email;
3
    var password = $scope.user.password;
4
    
5
    // Auth Logic will be here

6
}

ถัดไป ภายใต้ HomeCtrl ให้สร้าง Firebase instance โดยใช้ Firebase URL ดังนี้

1
var firebaseObj = new Firebase("https://blistering-heat-2473.firebaseio.com"); 

โมดูล $firebaseSimpleLogin นั้นถูกใช้เพื่อทำการ authenticate กับ Firebase โดยการใช้ email ID และ password เพื่อที่จะใช้งานมัน เราต้องการ inject โมดูล $firebaseSimpleLogin เข้าไปที่ HomeCtrl ดังแสดงด้านล่าง

1
.controller('HomeCtrl', ['$scope','$firebaseSimpleLogin',function($scope,$firebaseSimpleLogin) {

ด้วยการใช้ firebaseObj ให้สร้าง $firebaseSimpleLogin instance ดังโค้ดด้านล่าง

1
var loginObj = $firebaseSimpleLogin(firebaseObj);

จากนี้ ให้ใช้ $login API เราจะ authenticate ทั้ง email ID และ password กับ Firebase loginObj.$login นำเข้าทั้ง email และ password ในรูปแบบพารามิเตอร์ เมื่อทำการ authenticate สำเร็จแล้ว เราจะใช้ฟังก์ชัน success callback และเมื่อไม่สำเร็จ เราจะใช้ error callback

1
$scope.SignIn = function(event) {
2
    event.preventDefault();  // To prevent form refresh

3
    var username = $scope.user.email;
4
    var password = $scope.user.password;
5
    
6
    loginObj.$login('password', {
7
            email: username,
8
            password: password
9
        })
10
        .then(function(user) {
11
            // Success callback

12
            console.log('Authentication successful');
13
        }, function(error) {
14
            // Failure callback

15
            console.log('Authentication failure');
16
        });
17
}

ถัดไป สำหรับโค้ด controller ด้านบนที่ทำงานได้จริง เราต้องการใส่ controller เข้าไปใน view AngularJS นั้นมี directive ที่เรียกว่า ngController ไว้ให้ใส่ controller เข้าไปใน view เปิดไฟล์ home.html และเพิ่ม ngController directive เข้าไปในส่วนของ body element เพิ่มเชื่อมมันเข้ากับ HomeCtrl

เราต้องการ email และ password เพื่อที่จะให้เข้าถึงได้ภายในฟังก์ชัน SignIn controller  AngularJS นั้นจะให้ directive ที่ชื่อว่า ngModel เพื่อที่จะผูกกับค่า $scope ดังนั้นมันสามารถเข้าถึงได้ภายในฟังก์ชัน SignIn นั้น ใส่ ngModel directive ไปที่อิลิเมนต์ input ชื่อ email และ password ดังด้านล่าง

1
<body ng-controller="HomeCtrl">
2
3
    <div class="container">
4
        <div class="jumbotron" style="padding-bottom:0px;">
5
            <h2>AngularJS & Firebase App!</h2>
6
        </div>
7
        <form class="form-signin" role="form">
8
            <input ng-model="user.email" type="email" class="form-control" placeholder="Email address" required="" autofocus="">
9
            <input ng-model="user.password" type="password" class="form-control" placeholder="Password" required="">
10
            <label class="checkbox">
11
                <a href="#"> Sign Up</>
12
        </label>
13
        <button type="button" class="btn btn-lg btn-primary btn-block">SignIn</button>
14
      </form>
15
16
    </div>
17
18
  
19
20
</body>

สุดท้าย เพิ่ม ngClick directive เข้าไปที่ sign-in button เพื่อที่จะเรียกฟังก์ชัน SignIn 

1
<button type="button" ng-click="SignIn($event)" class="btn btn-lg btn-primary btn-block">SignIn</button>

บันทึกสิ่งที่ทำทั้งหมดและ restart server ชี้เบราว์เซอร์ของคุณไปที่ http://localhost:8000/app/index.html#/home และพยายาม sign in โดยใช้ email ID jay3dec@gmail.com และ password jay เมื่อทำการ authentication สำเร็จ เราสามารถเห็นข้อความ Authentication successful ใน console ของเบราว์เซอร์

สรุป

ในบทเรียนนี้ เราได้เริ่มการสร้างเว็บแอปพลิเคชันด้วย AngularJS เราได้ทำการ implement ฟังก์ชันการ sign-in และสามารถ authenticate user เข้าสู่ Firebase database ได้สำเร็จ

ในบทที่ 2 ของบทเรียนนี้ เราจะได้ทำสิ่งนี้ขึ้นไปอีกระดับด้วยการ implement validation และฟังก์ชันการ sign-up พร้อมกับฟีเจอร์อื่นๆ โค้ดที่ใช้ในบทเรียนนี้มีพร้อมให้แล้วบน Github

และอย่าลืมบอกให้เรารู้เกี่ยวกับความเห็นของคุณที่ช่องคอมเม้นต์ด้านล่างได้เลย

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.