FrontEnd

angular http 통신하기

고태광이 2019. 8. 3. 17:22

안녕하세요 오늘은  angular로 http 통신하는 법을 알아보려고 합니다.

 

먼저 httpClientModule을  app.module.ts 파일에 import 해주세요

import { HttpClientModule} from '@angular/common/http';

.........

 imports: [
  
     HttpClientModule

  ],

 

문서에서 http get 은 이런 형태로 디자인 되어있네요

        get(url: string, options: {
            headers?: HttpHeaders;
            observe: 'response';
            params?: HttpParams;
            reportProgress?: boolean;
            responseType?: 'json';
            withCredentials?: boolean;
        }): Observable<HttpResponse<Object>>;

 

option은 말 그대로 option이니까 선택사항이구요 url은 꼭 넣으셔야 합니다.

 

component에 httpClient를 import 합니다. 

(저는 videoList component를 만들었어요   - ng g c videoList)

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';

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

  constructor(private http: HttpClient) {}

  ngOnInit() {
  }

}

 

get videoList function 을 만들어줍니다.

    getVideoList() {
        this.http.get(this.baseUrl + '/videos').subscribe((res: any[]) => {
            console.log(res);
        });
    }

html 파일에는 간단하게 버튼 만들어줍니다.

<button (click)="getVideoList()">get videoList</button>

 

버튼을 누르면 콘솔에 이런식으로 나옵니다. ! 굳 !!!! 

 

화면에 보여줄때는 ngFor을 사용하면 간단하게 만들 수 있겠죠~