Step 6 Angular, JSON 데이터 HTTP 형식으로 받아오기
본문 바로가기

Interests [관심사]/Angular

Step 6 Angular, JSON 데이터 HTTP 형식으로 받아오기

json 형태의 데이터를  목록화 시켜서 출력 하도록 하겠습니다.


list-view.component.html


<ul class="list-group">
<li class="list-group-item" *ngfor="let color of colors">
{{color.name}} / {{color.code}}
</li>
</ul>


json 형식의 데이터파일을 만듭니다.

assets/data/color.json


[
{
"name" : "color01",
"code" : "a18ce9"
},
{
"name" : "color02",
"code" : "cf8ce9"
},
{
"name" : "color03",
"code" : "e88dd3"
},
{
"name" : "color04",
"code" : "e88ca5"
}

]


list-view.component.ts

HttpClientModule 을 import 해줍니다.

ngModule 에 import 하는것도 잊지 마세요 !


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


page-search.module.ts

interface 를 선언하고 colos : Color[] 배열을 선언합니다.


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

interface Color {
name : string;
code : string;
}

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

colors : Color[];

constructor(private http: HttpClient) {
this.http.get<color[]>('assets/data/color.json').subscribe(res =&gt; this.colors = res);
}

ngOnInit() {
}

}


완성 ~





color.json 데이터를 HTTP연결을 통하여 출력하는 방식 입니다. 어렵지 않아요 ^^