เรียนรู้ Angular part 1
เชื่อว่าหลายคนรู้จัก framework ตัวนี้ เขียนด้วยภาษา Typescript พร้อมด้วย concept หลายประการ ไม่ว่าจะเป็น Module, Component, Template and View, Component Metadata, Data Binding, Directive, Pipe, Service และ Dependency Injection
ใช้ framework อย่างถูกต้องก็จะได้ของดี หาไม่แล้วก็จะเละ
เราจะไม่พูดพื้นฐานมาก แต่ถ้าต้องพูดเราจะพล่ามมันให้มากที่สุด (จะดีเหรอ?) ผมแน่ใจว่าเพื่อนๆเคยสร้าง project ด้วย angular cli กันมาแล้ว ยกตัวอย่างเช่น
ng new <project-name>
จุดประสงค์ของ “Angular ด้วยตนเอง Deeper” นี้ จะนำเสนอ project ที่
- ทำตาม angular tutorial คือ The Tour of Heroes
- แบ่งชิ้นงานออกเป็น Module ย่อยๆแล้วเชื่อมันด้วย Router
- จัดการ UI state และ data state ด้วย Redux concept
- เลือก theme จาก Angular Material Design
- ใช้ Git และ GitLab เป็น repositories
- ทำ unit test
- อื่นๆไว้มาแก้ไขเพิ่มลดทีหลัง
มาสร้าง proejct กันก่อน หลังจากติดตั้ง angular cli เรียบร้อยแล้ว พิมพ์เลย
ng new tour-of-heroes
เรียบร้อยแล้วทดสอบรันเว็บ
ng serve
หรือถ้าอยากกำหนด port ด้วยก็พิมพ์เพิ่ม
ng serve --port 4200
เรียบร้อยแล้วทดสอบรัน test
ng test
ให้กลับไปดูไฟล์ package.json เพราะไฟล์นี้บรรจุประดา library ที่เป็น dependency ของ project นี้ทั้งหมด ดูในส่วนของ devDependencies
"devDependencies": {"@angular/compiler-cli": "^6.0.3","@angular-devkit/build-angular": "~0.6.8","typescript": "~2.7.2","@angular/cli": "~6.0.8","@angular/language-service": "^6.0.3","@types/jasmine": "~2.8.6","@types/jasminewd2": "~2.0.3","@types/node": "~8.9.4","codelyzer": "~4.2.1","jasmine-core": "~2.99.1","jasmine-spec-reporter": "~4.2.1","karma": "~1.7.1","karma-chrome-launcher": "~2.2.0","karma-coverage-istanbul-reporter": "~2.0.0","karma-jasmine": "~1.1.1","karma-jasmine-html-reporter": "^0.2.2","protractor": "~5.3.0","ts-node": "~5.0.1","tslint": "~5.9.1"}
ตามที่ error บอก “@types/jasmine”: “~2.8.6” ตรงนี้มีปัญหา ค้น Google อยู่พักก็ได้ว่าให้ลบเครื่องหมาย ~ นี้ออกไป ดังนั้นแก้ไขเป็น
"@types/jasmine": "2.8.6",
บันทึกแล้วรัน
npm install
เรียบร้อยแล้วตามด้วย
ng test
แต่ test case นี้ยังไม่ถูกต้อง เพราะมันแจ้งว่า AppComponent should render title in a h1 tag (ทีมผู้สร้างตั้งใจให้มันพังแบบนี้เพราะต้องการให้เราแก้ไขมัน)
ดังนั้นเปิดไฟล์ app.component.spec.ts
และนี่คือท่อนที่เกิดปัญหา
it('should render title in a h1 tag', async(() => {const fixture = TestBed.createComponent(AppComponent);fixture.detectChanges();const compiled = fixture.debugElement.nativeElement;expect(compiled.querySelector('h1').textContent).toContain('Welcome to tour-of-heroes!');}));
มันเขียน test case นี้ว่าภายในแท็ก h1 จะต้องมีข้อความ ‘Welcome to tour-of-heroes!’ แต่แท้จริงแล้วมันแสดง ‘Welcome to app!’ เหตุนี้ให้แก้ไขเป็น ‘Welcome to app!’ แล้วบันทึก
expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
เรื่องของ test เบื่องต้นไว้เท่านี้ก่อนนะครับ เราจะทำตาม angular tutorial — The Tour of Heroes ไปจนกว่าจะสิ้นลมหายใจ ช้าใย ไปอ่านดู
สัญญากับผมนะว่าเพื่อนๆจะอ่าน tutorial นี้เองหลังจากจบ part นี้ไปแล้ว เพื่อที่เราจะได้เข้าใจตรงกัน ว่าจุดไหนเน้นอะไรและอย่างไร จะได้เอามาคุยกันเน๊อะ