Project Angular-Tour-of-Heroes EP.5
Project Angular-Tour-of-Heroes EP.5 : Create MessagesComponent and
Create the MessageService
จาก ep.4 ที่เราได้ทำ service มาตัวหนึ่ง ที่เป็น Observable และ Subscribe เพื่อรอฟังการเปลี่ยนแปลงจากฟังที่ส่งข้อมูล ครั้งนี้เราจะมาต่อกัน เราจะทำให้แสดง Message
EP.4 การทำ Service
Show Message
การที่จะเอา messages มาแสดงได้ นั้นเราจะสร้าง component มาตัวหนึ่งชื่อว่า MessageComponent
เราจะทำต่อจาก project เดิม angular-tour-of -heroes มาต่อกันเลย เริ่มการสร้าง component มาตัวหนึ่งชื่อว่า messagesด้วยคำสั่ง
ng g component components/message
และไปแก้ไขที่ไฟล์ app.component.html และเพิ่ม tag <app-message></app-message> นี้ลงไป เมื่อเรารันแล้วจะเป็นว่าไปแสดงที่ข้างล่างสุดของเพจ
Create MessageService
การสร้าง MessageService ด้วยคำสั่งนี้
ng g service services/message
เปิดเข้าไปที่ไฟล์ message.service.ts และเพิ่มโค้ดดังนี้ลงไป สร้างตัวแปร ที่มีค่าเป็น stringเก็บค่าที่เป็น array [] และเพิ่มmethods ลงไป 2 ตัว คือ method : add() และ method : clear()
เมื่อเราสร้าง methods นี้เสร็จแล้ว จะเรา Inject มาใช้ที่ไฟล์ hero.service.ts ดังนี้
การส่ง message จาก HeroService
แก้ไข method : getHeroes() เพื่อส่ง message เมื่อ heroes ถูกเรียก
การแสดง message จาก HeroService
เราจะให้ message มาแสดงที่ MessagesComponent โดย message ส่งมาจาก HeroService เมื่อดึงข้อมูลจาก heroes
เปิด MessagesComponent ไฟล์ messages.component.ts และ import MessageService มาใช้งาน
แก้ไข constructor กับ parameter ประกาศเป็น public messageService inject : messageService มาใช้
ผูก MessagesService กับ Template ที่ไฟล์ messages.component.html ดังนี้
เพิ่ม messages ให้กับ hero service
จะให้ส่ง และ แสดง Message ทุกครั้งที่คลิกเลือก hero จะโชว์ รายละเอียด โดยไปที่ไฟล์ heroes.component.ts ดังนี้
inject : messageService
private messageService:MessageService
นำ Method : add() มาใช้งานที่ Method : onSelect()
this.messageService.add(`HeroesComponent: Selected hero id=${hero.id}`);
ภาพโดยรวม
การตกแต่ง css ไฟล์ message.component.css
h2 {
color: red;
font-family: Arial, Helvetica, sans-serif;
font-weight: lighter;
}body {
margin: 2em;
}body, input[text], button {
color: crimson;
font-family: Cambria, Georgia;
}button.clear {
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
cursor: hand;
}button:hover {
background-color: #cfd8dc;
}button:disabled {
background-color: #eee;
color: #aaa;
cursor: auto;
}button.clear {
color: #333;
margin-bottom: 12px;
}
บันทึกแล้วดูที่ตัวอย่าง localhost:4200 คำสั่งรัน ng serve
ep. นี้เราสามารถทำให้เคลียหรือลบได้แล้ว เมื่อเราคลิกเลือก hero ID จะมาแสดง และเราสามารถลบ ID นั้นออก ep. หน้าเราจะไปต่อเรื่องการ Navigation with Routing กำหนดเส้นทาง ที่ Data จะแสดง ^_^
อ้างอิงจาก Angular Tutorials