🅰️ Angular에서 실시간 데이터 스트림 처리 및 UI 반응형 구현

Angular 예제

중급 난이도
예제 타입
11/12 등록일

Angular에서 실시간 데이터 스트림 처리 및 UI 반응형 구현

중급
태그
예제 실습 프로젝트 rxjs observable 실시간데이터 UI반응형
## 프로젝트 개요
실시간으로 업데이트되는 데이터를 Angular 애플리케이션에 반영하고, 사용자 인터페이스가 자동으로 반응하도록 하는 예제입니다. 이는 실무에서 주로 웹 소켓이나 HTTP 서버推送을 통해 전달받는 데이터 처리 시 유용합니다.

## 주요 기능
- Observable을 활용한 실시간 데이터 스트림 처리
- UI에 실시간 데이터 반영
- 오류 처리 및 로깅 기능 포함
- 사용자 입력으로 데이터 요청 및 필터링

## 사용 방법
1. Angular CLI를 통해 프로젝트 생성 후 이 코드를 복사하여 src/app 폴더에 붙여넣기
2. 필요한 의존성(예: rxjs)을 설치 후 실행
3. 브라우저에서 애플리케이션 실행

## 확장 가능성
- WebSocket을 사용한 실시간 데이터 통신 구현
- 데이터 저장 및 로컬 스토리지 연동
- 데이터 시각화 라이브러리(예: Chart.js)와의 연동
코드 예제
// src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable, interval, of, Subject } from 'rxjs';
import { map, filter, switchMap, catchError, tap } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'realtime-data-app';
  dataStream$: Observable<any>;
  filteredData: any[] = [];
  errorMessage: string | null = null;

  constructor() {}

  ngOnInit(): void {
    // 실시간 데이터 스트림을 시뮬레이션 (예: 매 초 새로운 데이터 전송)
    this.dataStream$ = interval(1000).pipe(
      map(i => ({
        id: i,
        value: Math.floor(Math.random() * 100) + 1,
        timestamp: new Date().toISOString()
      })),
      tap(data => console.log('Received data:', data))
    );

    // 사용자 입력에 따라 필터링 로직 추가 (예: 특정 값 이상인 데이터만 표시)
    const filterSubject = new Subject<number>();
    this.dataStream$ = this.dataStream$.pipe(
      switchMap(data => 
        data.value >= filterSubject.getValue() ? of(data) : of(null)
      ),
      filter(data => data !== null),
      catchError(error => {
        console.error('Error fetching data:', error);
        return of({ error: '데이터를 불러오는 중 오류가 발생했습니다.' });
      })
    );

    // 사용자 입력 처리 (예: 필터링 값 설정)
    this.dataStream$.subscribe(data => {
      if (data.error) {
        this.errorMessage = data.error;
        this.filteredData = [];
      } else {
        this.filteredData.push(data);
        this.errorMessage = null;
      }
    });
  }

  applyFilter(value: number): void {
    filterSubject.next(value);
  }
}

// src/app/app.component.html
<div>
  <h2>실시간 데이터 스트림 예제</h2>
  <p>{{ title }}</p>
  <div>
    <label for="filter">필터링 값 (값 이상인 데이터만 표시): </label>
    <input type="number" id="filter" [(ngModel)]="filterValue" name="filter">
    <button (click)="applyFilter(filterValue)">필터 적용</button>
  </div>
  <div *ngIf="errorMessage">
    <p style="color: red">{{ errorMessage }}</p>
  </div>
  <ul>
    <li *ngFor="let item of filteredData">
      {{ item.id }} - {{ item.value }} ({{ item.timestamp }})
    </li>
  </ul>
</div>

// src/app/app.component.css
/* 기본 스타일 */
body {
  font-family: Arial, sans-serif;
}

input[type="number"] {
  padding: 8px;
  margin-right: 10px;
}

button {
  padding: 8px 16px;
  cursor: pointer;
}
등록일: 2025년 11월 12일 02:31
언어 정보
언어
Angular
카테고리
Web
인기도
#13
학습 팁
코드를 직접 실행해보세요
변수를 바꿔가며 실험해보세요
오류가 나도 포기하지 마세요
다른 예제도 찾아보세요