FrontEnd

angular http 통신 code refactoring

고태광이 2019. 8. 3. 18:06

안녕하세요 전 포스트에서는 angular http 통신을 알아봤는데요.

간단하게 알아보느라 거기에는 한 파일에 여러 코드를 작성했습니다. 

따라서 이번 글에서는 리팩토링을 하려고 합니다. 

 

1. http 통신하는 서비스 

2. video 모델  

 

이런식으로 분리하겠습니다.

 

서비스를 만듭니다.

ng g s restService
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RestServiceService {
  baserUrl = 'http://localhost:8081';
  constructor(private httpClient: HttpClient) { }

  getVideoList() {
      return this.httpClient.get(this.baserUrl + '/videos');
  }
}

  위와 같이  통신만을 위한 서비스를 만들었습니다. 이러면 각 컴퍼넌트에서  httpClient 사용할 필요없이 이 서비스만 사용하면 되겠죠 :)

 

 

모델을 만듭니다. 

export interface VideoSample {
    id: string,
    url: string,
    thumnailUrl: string,
    title: string
}

위와 같이 모델을 만들면 모델이 변경될때마다 이 파일만 변경하면 되니까 훨씬 관리하기 쉽겠죠

 

 

만든 코드들을 바탕으로 컴퍼넌트 수정하면 됩니다.

import {Component, OnInit} from '@angular/core';
import {RestServiceService} from '../rest-service.service';
import {VideoSample} from '../model/videoSample';

@Component({
    selector: 'app-video-list',
    templateUrl: './video-list.component.html',
    styleUrls: ['./video-list.component.css']
})
export class VideoListComponent implements OnInit {
    private videos: VideoSample[] = [];

    constructor(private restService: RestServiceService) {
        this.restService.getVideoList().subscribe((res: VideoSample[]) => {
            this.videos = res;
        });

    }

    ngOnInit() {
    }

}

 

위와 같이 서비스를 사용하고, 함수 하나면 끝입니다! 훨씬 깔끔해졌네요