Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- formgroup
- ajax 사용 예시
- ApexChart
- modal
- 검색
- TAILWIND
- 앵귤러 모달
- angular route
- angular animation
- mysql if
- 모달
- Ionic modal
- 옵저버블
- scroll
- 아이오닉 스크롤 이벤트
- 스크롤 이벤트 감지
- angular button
- summary
- flex-1
- Angular Router
- 스크롤 이벤트
- prisma
- 셀렉트박스 커스텀
- route
- Router
- egov spring ajax 사용 예시
- angular modal
- 앵귤러 애니메이션
- Oracle LISTAGG 사용 예시
- 호버
Archives
- Today
- Total
깜놀하는 해므찌로
Angular Observable HTTP 앵귤러 HTTP 통신 feat.Observable 예시 본문
반응형
SMALL
0. HTTP 통신을 위해 app.config 에 모듈을 로드합니다.
npx nx generate service --project 프로젝트명
1. cli 를 활룔해 http 서비스를 생성합니다.
2. 통신과 관련된 url 상수값을 선언하기 위해 environment.ts 파일 폴더 및 파일을 생성합니다.
3. 제 경우 여러 곳에 요청을 할 것이므로 각각 요청할 서버 위치가 섞이면 헷갈리 수 있으므로 여러개 있는 것입니다.
4. 이번 예시에서는 하나만 사용합니다.
5. 백엔드 서버에서는 baseUrl 과 projectId 두 개를 받아 해당 프로젝트의 데이터를 DB에서 조회해 리턴하도록 코드가 이미 짜여진 상태입니다.
import { Injectable } from '@angular/core';
import {
HttpClient,
HttpContext,
HttpHeaders,
HttpParams,
} from '@angular/common/http'; // HTTP 통신을 위해 로드
import { environment } from '../../environments/environment'; // 방금 전에 만든 서버 관련 상수값 로드
export type HttpServiceOptions = {
headers?:
| HttpHeaders
| {
[header: string]: string | string[];
};
context?: HttpContext;
observe?: 'body';
params?:
| HttpParams
| {
[param: string]:
| string
| number
| boolean
| ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
};
@Injectable({
providedIn: 'root',
})
export class HttpService {
private readonly baseUrl = `${environment.baseUrl}`; // 상수 baseUrl 속성에 할당
constructor(private readonly httpClient: HttpClient) {}
get<T>(url: string, option?: HttpServiceOptions) { // 조회용
return this.httpClient.get<T>(`${this.baseUrl}/${url}`, {
...option,
});
}
post<T>(url: string, body: any, option?: HttpServiceOptions) { // 데이터 전송
return this.httpClient.post<T>(`${this.baseUrl}/${url}`, body, {
...option,
});
}
put<T>(url: string, body: any, option?: HttpServiceOptions) { // 데이터 전송
return this.httpClient.put<T>(`${this.baseUrl}/${url}`, body, {
...option,
});
}
patch<T>(url: string, body: any, option?: HttpServiceOptions) { // 수정
return this.httpClient.patch<T>(`${this.baseUrl}/${url}`, body, {
...option,
});
}
delete<T>(url: string, option?: HttpServiceOptions) { // 삭제
return this.httpClient.delete<T>(`${this.baseUrl}/${url}`, {
...option,
});
}
}
6. 서비스 부분입니다. 자세한 설명은 주석을 참조해주세요.
7. 이번 예시에서는 데이터를 조회하는 부분만 보도록 하겠습니다.
import { HttpService } from '../../services/http.service';
import { environment } from 'apps/client/src/environments/environment';
constructor(
private scrollService: ScrollService,
private router: Router,
private httpService: HttpService // 좀 전에 생성한 서비스 의존성 주입
) {}
ngOnInit() { // 페이지 첫 로드 시 데이터를 조회하도록 onInit 후크에서 호출
this.getItems();
}
getItems() { // 데이터 조회 메소드 선언
this.httpService
.get<any>(`${environment.projectId}`)
.subscribe({ // httpService.get : 메소드는 observable 타입을 리턴하므로 곧바로 subscribe 구독
next: (res) => { // res: 임의로 정한 변수명으로 이 인스턴스에는 서버로부터 받은 응답데이터가 담겨있습니다.
console.log(res); // 출력으로 알맞게 데이터가 도착했는지 확인
},
});
}
8. 데이터를 조회할 아무 컴포넌트에 좀 전에 생성한 서비스를 주입하고 활용하는 예시입니다.
반응형
LIST
'IT' 카테고리의 다른 글
Ionic Angular loading 앵귤러 로딩 페이지 서비스 예시 (0) | 2023.07.14 |
---|---|
Angular Ionic에서 Kakao Map API 사용하기 (0) | 2023.07.13 |
Ionic Angular mobile side Menu / 아이오닉 앵귤러 모바일 사이드 메뉴 구현 예시 / ionic menu / ion-menu (1) | 2023.07.11 |
Ionic angular router page changed scrollTop / 페이지 이동 시 최상단 고정 예시 (0) | 2023.07.10 |
Ion Scroll listen 활용 예시 / RxJS observable service (0) | 2023.07.09 |