카테고리 없음

[Angular] Angular Rest API Call(호출)

Mr.Walker 2020. 3. 23. 17:26
반응형

!주의

본 포스트는 djamware.com의 example을 참고하여 작성되었습니다.

부족한 내용이나 이해가 되지 않는 부분은 하단의 원글을 참고하시면 됩니다.

https://www.djamware.com/post/5b87894280aca74669894414/angular-6-httpclient-consume-restful-api-example

 

Angular 6 HttpClient: Consume RESTful API Example

A comprehensive step by step Angular 6 HttpClient tutorial on consuming RESTAPI service from the remote server

www.djamware.com

 

 

이번 포스트는 Angular에서 Rest API를 호출 하는 방법을 다뤄보겠습니다.

 

Rest API를 호출하기 위해선 App.module에 HttpClient를 추가해야합니다.

src/app/app.module.ts

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

imports: [
  BrowserModule,
  HttpClientModule
]

 

상단의 코드를 해당 위치에 작성하는 것으로 Angular에 HttpClient를 사용할 수 있게 됩니다.

그리고 Service에 하단의 코드를 추가합니다.

rest.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';

const endpoint = 'Rest API Adress';
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};

 

* RxJx

비동기 데이터 스트림을 처리하는 API를 제공하는 자바스크립트 라이브러리

 

Rest API와 비동기 통신으로 주고 받기 때문에 이를 지원하는 RxJx를 사용합니다.

endpoint로 통신할 Rest Api 주소를 지정합니다.

RxJx는 옵저버블과 옵저버로 서로간의 데이터를 주고 받습니다. 그리고 통신할 때 JSON 포멧으로 주고 받기 때문에

Content-Type: 'application/json' 으로 지정합니다.

 

rest.service.ts
//생략
export class RestService {
	constructor(private http: HttpClient) { }
    
    private extractData(res: Response) {
  		let body = res;
 		return body || { };
	}
    
    getProducts(): Observable<any> {
  		return this.http.get(endpoint + 'products').pipe(
    	map(this.extractData));
	}
    
    //생략
}

 

constructor에 HttpClient Module을 주입합니다.

다른 type checker를 사용하지 않고 JSON 포멧의 데이터를 추출하기 위해 extractData 메서드를 작성했습니다.

 

Rest API를 호출하기 위한 메서드를 작성합니다.

getProducts()와 같은 형식으로 Rest API 호출 메서드를 작성합니다.

 

return this.http.get(endpoint + 'Rest API Request Mapping Adress', 'Observale 변수').pipe(
	map(Restservice.extractData));

 

Component에서 아래와 같은 형식으로 호출 할 수 가 있습니다.

 

Products.component.ts
//생략
getProducts() {
    this.products = [];
    this.rest.getProducts().subscribe((data: {}) => {
      console.log(data);
      this.products = data;
    });

 

이렇게 Component에서 만든 메서드를 Html에서 사용하면 정상적으로 Rest API와 호출 또는 연동이 되는 것을

할 수 있습니다.

 

앞서 말했다시피 자세한 내용은 상단의 원문을 통해서 알 수 있습니다.

 

 

 

 

반응형