[Angular Tutorial 05] Services
본문 바로가기

Interests [관심사]/Angular

[Angular Tutorial 05] Services

[Angular Tutorial 05] Services

 https://angular.io/tutorial/toh-pt4


Service는 여러 component에서 필요로 하는 기능을 묶은 class입니다. 즉 Angular 사이트에서 사용되는 특정한 기능들을 service로 생성한 후 해당 기능이 요구되는 component는 이 service를 불러와서 사용할 수 있습니다. 코드가 중복되는 것을 막고, 코드의 관리의 편의성을 위해, 프로그램의 효율성 향상를 위해 사용됩니다.

출처 : https://www.a-mean-blog.com/ko/blog/Angular-2/Tour-of-Heroes/Services-Injectable-OnInit-ngOnInit


다음 명령어를 통해서 hero service 를 생성 합니다.

 ng generate service hero 



다음과같은 구조로 생성이 되며 자동으로 생성 된 코드는 아래와 같습니다.


import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class HeroService {

constructor() { }
}



이제 service 에 데이터를 받아 옵니다.

hero 와 mock-heroes 파일을 import 하고 getHeroes() 함수를 작성 합니다.


import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable({
providedIn: 'root'
})
export class HeroService {
getHeroes(): Hero[] {
return HEROES;
}
constructor() { }
}



만들어진 service 를 HeroesComponent 에 import 시킵니다. src/app/heroes/heroes.component.ts (import HeroService)

Heroes.component.ts 코드를 아래와 같이 수정 합니다.


import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';

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

// heroes = HEROES; 기존 코드
heroes: Hero[]; //변경 된 코드

selectedHero: Hero;
onSelect(hero: Hero): void {
this.selectedHero = hero;
}

//Add a private heroService parameter of type HeroService to the constructor.
constructor(private heroService: HeroService) { }

//Create a function to retrieve the heroes from the service.
getHeroes(): void {
this.heroes = this.heroService.getHeroes();
}

//While you could call getHeroes() in the constructor, that's not the best practice.
ngOnInit() {
this.getHeroes();
}

}


여기까지도 기능상의 큰 변화는 없습니다. 서버를 실행 시켜서 이전과 같이 정상적으로 작동하는지 확인 합니다.



정상적으로 작동이 확인 되면 src/app/hero.service.ts (Observable imports) 파일에 rxjs library 를 import 합니다.

그리고 getHeroes() 함수를 다음과 같이 수정 합니다. 


import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Observable, of } from 'rxjs';

// 해당 class를 service로 만들어 준다.
@Injectable({
providedIn: 'root'
})
export class HeroService {
getHeroes(): Observable<Hero[]> {
return of(HEROES);
}
constructor() { }
}


of(HEROES) returns an Observable<Hero[]> that emits a single value, the array of mock heroes.


heroes.component.ts 의 getHeroes() 함수를 다음과 같이 수정 해줍니다.


getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}