Http 통신 예시_초간단 사용자 조회 어플리케이션
모든 내용은 앵귤러 첫걸음 책을 기반으로 합니다.
사용자 조회 어플 프로젝트 생성
ng new contacts-manager --prefix=cm
AppModule 수정
- app.module.ts 파일 클릭_추가
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
- 하단 지시자 imports 추가
imports: [
BrowserModule,
FormsModule,
HttpModule,
],
user 서비스 생성하기
- user폴더 생성
- console 창으로 서비스 생성하기
mkdir user/user
ng g service user/user
- user.model.ts 파일 생성 및 User선언
export class User{
id : number;
name : string;
age : number;
constructor(){
this.id = 0;
this.name = '';
this.age = 0;
}
}
import 'rxjs/add/operator/map'
RxJS와 같은 애플리케이션 전반에 걸쳐 사용하는 코드는 임포트문을 한 곳에서 임포트하는 것이 좋다.
app.component.html 파일 수정
- id, name, age 현재 양방향 바인딩 상태
- 찾기, 삭제, 수정 버튼 이벤트 바인딩 선언 상태
<h2>Contact Manager : Http 실습</h2>
<div>
<h4>사용자 조회 / 삭제 </h4>
<label for="user-no">사용자 Id : </label>
<input type="number" name="user-id" #userIdInput>
<button type="button" (click)="findUser(userIdInput.value)">검색</button>
<button type="button" (click)="removeUser(userIdInput.value)">삭제</button>
<!-- 파이프로 json을 사용했네 -->
<div></div>
</div>
<div>
<h4>사용자 등록 / 수정</h4>
<label for="user-id">사용자 ID : </label>
<input type="number" name="user-id" [(ngModel)]="user.id"><br>
<label for="user-name">사용자 이름 :</label>
<input type="text" name="user-name" [(ngModel)]="user.name"><br>
<label for="user-age">사용자 나이 : </label>
<input type="number" for="user-age" [(ngModel)]="user.age"><br>
<button type="button" (click)="modifyuser()">사용자 등록/수정</button>
</div>
찾기, 삭제, 수정 구현
- app.component.ts 수정
- import 추가
import { User } from './user/user.model';
import { UserService } from './user/user.service';
예상되는 에러 상황
import ‘rxjs/add/operator/map’에서 에러가 뜨는 경우
- rxjs 설치를 완료후 실행하면 완료
npm install rxjs