메뉴 구성
todo 컴포넌트를 생성.
1 |
ng g component todo |
app.module.ts에 라우팅 path를 설정한다.
1 |
{path: 'todo', component: TodoComponent} |
app.component.html에 메뉴 링크 추가하고 좌우 화면 폭을 줄인다.
1 2 3 4 5 6 7 8 |
<li class="nav-item" routerLinkActive="active"> <a class="nav-link" href routerLink="/todo">todo</a> </li> ... <div class="container p-3"> <router-outlet></router-outlet> </div> |
이제 todo 메뉴를 누르면 todo works가 보여야 한다.
화면 구성
할일 목록 보기 화면을 구성한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<table class="table table-striped"> <thead> <tr> <th>완료</th> <th>todo</th> <th>생성일</th> <th>수정일</th> <th>삭제</th> </tr> </thead> <tbody> <tr> <td>완료</td> <td>빨래하기</td> <td>2018-06-01</td> <td>2018-06-01</td> <td> <button class="btn btn-success btn-sm">수정</button> <button class="btn btn-danger btn-sm ml-1">삭제</button> </td> </tr> </tbody> </table> |
객체 정의
먼저 postman으로 REST api를 테스트하고 리턴되는 결과를 보고 받을 객체를 정의한다.
domain폴더를 추가하고 todo.vo.ts 화일에 다음과 같이 타입을 정의한다.
1 2 3 4 5 6 7 |
export class TodoVo { todo_id: number; isFinished: boolean; todo: string; created: string; updated: string; } |
서비스 구현
1 2 3 |
getTodoList(): Observable<TodoVo[]> { return this.http.get<TodoVo[]>(environment.HOST + '/api/todo'); } |
Get 메서드는 body가 없으므로 첫번째 파라메터에 프로토콜만 넣어준다.
리턴타입은 Json Array에 TodoVo 객체로 넘어오므로 TodoVo[] 타입으로 정의한다. 리턴 타입을 정의하면 컴포넌트에서 호출해서 불러쓰기가 쉽다.
서비스 호출 및 모델 생성
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
export class TodoComponent implements OnInit { todoList: TodoVo[]; constructor(private heroService: HeroService) { } ngOnInit() { this.getTodoList(); } getTodoList() { this.heroService.getTodoList() .subscribe(body => { console.log('getTodoList', body); this.todoList = body; }); } } |
제대로 받았는지 개발자 콘솔에서 확인해보자.
모델을 뷰에 바인딩하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<table class="table table-striped"> <thead> <tr> <th>완료</th> <th>todo</th> <th>생성일</th> <th>수정일</th> <th>삭제</th> </tr> </thead> <tbody> <tr *ngFor="let todo of todoList"> <td>{{todo.isFinished ? '완료' : '미완료'}}</td> <td>{{todo.todo}}</td> <td>{{todo.created}}</td> <td>{{todo.updated}}</td> <td> <button class="btn btn-success btn-sm">수정</button> <button class="btn btn-danger btn-sm ml-1">삭제</button> </td> </tr> </tbody> </table> |
컴포넌트 기반 개발 방식은 뷰를 조작하는게 아니라 모델 정보를 업데이트하고 모델과 뷰를 바인딩 시킨다는 개념을 기억하자.
이미 모델을 생성하였고, 이제 뷰를 모델 데이터와 바인딩 시키기만 하면 된다. ngFor를 이용한 반복문과 interpolation ({{}})문법을 이용하여 바인딩하자.