- Home Component 생성 -
이번 포스팅에서는 MVC 패턴에서 Model역할을 담당하는 Home Component를 알아보자. Nav Component가 MVC패턴의 컨트롤러라면, Home컴포넌트는 모델에 해당한다. 데이터값이 저장되는 그릇과 같은 역할을 하기 때문이다.
1. 명령어 실행
-> ng g c Home ( Home 컴포넌트 생성 )
-> ng g class Post ( post 클래스 단일 파일 생성 )
post.ts 클래스 단일파일은 왜 생성할까? node.js Express + Angular 첫 포스팅에서 models 폴더 아래에 post.js 파일을 생성했었다. post.js 파일은 일종의 DB 항목들이 적혀있는 명세서다. Angular에서 DB를 활용하기 위해서는 몽고DB의 스키마처럼 DB 데이터의 항목들이 있는 명세서가 필요하다. post.js 클래스 파일이 바로 이 역할을 한다.
2. post.ts 수정
post.js와 거의 흡사하다. 다만 객체 문법에 따라서, 문장끝에 ,를 빼고, ;를 넣어준다.
3. Home.component.ts 수정
Home 컴포넌트에서 DB데이터를 사용할 때, post.ts 모듈을 참고하므로 import 구문을 실행한다.
//코드
import { Component, OnInit } from '@angular/core';
import { PostService } from '../post.service'
import { Post } from '../post';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
posts:Array<Post>;
constructor(private _postService:PostService) { }
ngOnInit( ) {
this._postService.getPosts( )
.subscribe( res => this.posts = res )
}
}
- DB의 항목을 기술해놓은 post를 임포트(호출)한다.
- HomeComponent 클래스에서 posts 변수에 <Post>를 설정해서 배열값 방식을 설정한다.
- constructor 구문에서 지난 번에 만들어놓은 PostService를 _postService에 상속한다.
- ngOnInit() 함수를 만들고, 상속받은 PostService에 있는 getPosts( ) 매소드(/api/posts 의 데이터를 받아오는)를 .subscribe한다.
- .subscribe는 json데이터를 갖고 와서, res에 넣고, res값을 posts에 <Post>형식의 배열로 넣어주는 역할을 한다.
4. HomeComponent.html 수정
//코드
<div class="row">
<div class="columns small-12 medium-6 large-4">
<div class="post-container">
<div class="row">
<div class="columns small-12 large-10">
<a routerLink="/" class="post-title">Create a Mean Steak App in Angular 4 </a>
</div>
<div class="columns small-12 large-2 show-for-large">
<a href="#" target="_blank" class="external">
<!--svg 삽입 -->
</a>
</div>
</div>
<p> Our description here</p>
<a routerLink="/" class="cta-btn btn2">More Info</a>
</div>
</div>
</div>
-> Home 컴포넌트의 상단 메뉴가 끝난 뒤 본격적으로 시작되는 Main 첫 항목이다.
-> 부트스트랩처럼 foundation 역시 class="row" -> class="clumns" 식의 구조를 가진다.
-> foundation 역시 그리드 시스템으로 총 12 그리드가 있으며, 12그리드 내에서 크기를 조절해준다.
-> columns small-12 라는 의미는 스마트폰 크기로 줄였을 때, 이 부분이 12크기(전체)로 나온다는 의미이다.
-> 여기서 Angular만의 특점은 Angular에서는 <a>태그를 사용하지 않고, 라우터를 걸 때는 routerLink를 사용한다.
-> routerLink를 사용하려면 app.routing.ts 파일을 설정해야 한다.
5. app-routing.module.ts 수정
//코드
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{
path: '',component:HomeComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
-> HomeComponent 파일을 import한다.
-> routes:Routes 부분에 path는 라우터 주소를 의미한다. 여기서 '/'를 붙이지 말자.
-> component:(path 주소로 라우팅 할 컴포넌트 이름) 이렇게 두 가지만 설정해주면 라우팅이 끝난다. 간단하다.
-> cmd에서 ng build -> node server.js를 실행하면 아래와 같은 페이지가 나타난다.
Mlab.com의 데이터를 가져오기 위해서는, 아래와 같이 *ngFor=" let (변수이름) of (/api/posts로 내보낸 DB Json 데이터 이름)"을 지정하고, {{ (변수이름).속성 }}을 입력한다.
//결과
'코드 스터디' 카테고리의 다른 글
Mean스텍 입문 (8) - Details Component 만들기 - (0) | 2017.07.20 |
---|---|
Mean스텍 입문 (7) - Home Styling - (0) | 2017.07.20 |
Mean스텍 입문 (5) - Nav Component 작성하기 - (0) | 2017.07.19 |
Mean스텍 입문 (4) - Angular 서비스 설정- (0) | 2017.07.19 |
Mean스텍 입문 (3) Angular 프론트에서 데이터베이스와 연결하기 (0) | 2017.07.18 |
댓글