this.route.params
this.route.params
- 이 값은 단순한 객체가 아닙니다.
- Observable입니다.
- URL 파라미터가 바뀔 때마다
- 새로운 값이 흘러나오는 스트림입니다.
this.route.params.subscribe(params => {
console.log(params);
});
- 위 코드는"URL 파라미터가 바뀔 때마다 실행해 줘" 입니다.
Observable은 왜 바로 쓰면 안 될까?
아래 코드는 처음엔 문제가 없어 보입니다.
this.route.params.subscribe(params => {
const id = params['id'];
this.loadData(id);
});
하지만 실무에서 이런 문제가 생깁니다.
- 조건 분기 추가
- 파라미터 가공
- API 연쇄 호출
- 구독 해제 로직
그러면 subscribe 안이 점점 비대해집니다.
pipe
pipe는 Observable에서 흘러오는 값을 가공하는 연산자(operator) 연결 통로입니다
observable.pipe(
operator1(),
operator2(),
operator3()
)
- 값이 들어오면
- 위에서부터 아래로
- 순서대로 처리됩니다.
pipe를 쓰지 않은 코드 vs 쓴 코드
pipe 없이 작성한 코드
this.route.params.subscribe(params => {
const id = params['id'];
if (!id) return;
this.service.getDetail(id).subscribe(data => {
this.detail = data;
});
});
- subscribe 중첩
- 로직 추적 어려움
- 테스트 힘듦
pipe를 사용한 코드
this.route.params.pipe(
map(params => params['id']),
filter(id => !!id),
switchMap(id => this.service.getDetail(id))
).subscribe(data => {
this.detail = data;
});
- 데이터 흐름이 위 → 아래로 명확
- subscribe는 결과만 받음
- 유지보수 쉬움
pipe 안에서 가장 많이 쓰는 연산자들
map – 값 변환
map(params => params['id'])
- params 객체 → id 값
- 값의 형태를 바꾸는 역할
filter – 조건 통과
filter(id => !!id)
- falsy 값 제거
- undefined, null 방어용으로 자주 사용
tap – 중간 확인 (디버깅)
tap(id => console.log(id))
- 값을 바꾸지 않음
- 로그, 로딩 처리 등에 사용
switchMap – Observable 교체 (핵심)
switchMap(id => this.service.getDetail(id))
- 새로운 Observable로 갈아탐
- 이전 요청 자동 취소
- 라우터 + API 조합에서 거의 필수
왜 switchMap을 써야 할까?
map + subscribe 조합
this.route.params.pipe(
map(params => params['id'])
).subscribe(id => {
this.service.getDetail(id).subscribe(...);
});
- 중첩 subscribe
- URL 빠르게 바뀌면 이전 요청 살아 있음
switchMap 사용
this.route.params.pipe(
map(params => params['id']),
switchMap(id => this.service.getDetail(id))
).subscribe(data => {
this.detail = data;
});
- 이전 요청 자동 취소
- 최신 값만 유지
pipe는 실행하는 게 아닙니다.
this.route.params.pipe(
map(...)
);
- 아무 일도 안 일어납니다.
this.route.params.pipe(
map(...)
).subscribe();
- 여기서부터 실행됩니다.
Angular 실무에서 자주 쓰는 패턴
라우터 파라미터 + API 호출
this.route.params.pipe(
map(p => p['id']),
distinctUntilChanged(),
switchMap(id => this.api.getDetail(id)),
takeUntil(this.destroy$)
).subscribe(data => {
this.detail = data;
});
- 동일 id 중복 호출 방지
- 컴포넌트 destroy 시 자동 해제
'개발 공부 > Angular' 카테고리의 다른 글
| 탭 간 상태 동기화 (0) | 2025.12.19 |
|---|---|
| Angular validationForm 2 예시 (0) | 2025.12.16 |
| Angular validationForm (0) | 2025.12.14 |
| 앵귤러 메타데이터 관리 (2) (0) | 2025.12.02 |
| 앵귤러 메타데이터 관리 (1) (0) | 2025.11.30 |