Angular로 개발하기 - 2
서비스와 의존성 주입
서비스는 애플리케이션의 비즈니스 로직을 담는 클래스이다. 서비스를 이용하는 이유는 컴포넌트에서 비즈니스 로직을 분리하기 위해서이다.
일단 서비스를 만들어보자!
ng g service 서비스(클래스)명
서비스를 생성하고 나면 서비스명.service.ts와 서비스명.service.ts 파일이 생성된다
~.service.ts : 속성들과 메소드들로 이루어지는 서비스의 핵심적인 파일이다.
~.service.spec.ts : 테스트를 위해서 만들어지는 파일이다. (테스트관련은 추후 공부 예정)
ser-a.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class SerAService {
constructor() { }
}
코드를 보면 알겠지만 컴포넌트 생성시 @Component
이런 부분인 @Injectable
로 변경되었음을 알 수 있다. 뭔가 의존성이라는 뜻이고 의존성을 주입하는데 사용하겠다는 이야기이다. 별거없는 내용이지만 코드를 보면서 설명을하면 확실히 이해가 금방 될 것이다.
예제를 사용하기위해 지난번에 포스팅했던 app.component.html의 내용을 a.component.html로 옮기겠다.
a.component.html
<h4><span>{{number}}</span> 알파벳 입니다.</h4>
<div class="contents">
<label for="user-name">name: </label>
<input type="text" name="user-name" id="user-name" #nameInput>
<button type="button" (click)="setNumber()">submit</button>
</div>
일반적인 설명을 위해 내용도 조금 수정했으니 참고바란다.
a.component.ts
import { Component, OnInit } from '@angular/core';
import { SerAService } from '../ser-a.service'; //일단 생성한 서비스 임포트
@Component({
selector: 'app-a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.css']
})
export class AComponent implements OnInit {
number = "";
constructor(public serSupporter: SerAService) {} //핵심
setNumber(name) {
this.number = this.serSupporter.methodA(this.number, 'a');
}
ngOnInit() {
}
}
constructor(public serSupporter: SerAService) {}
이 줄이 사실 의존성 주입의 핵심이다. 의존성 주입이란 임포트한 SerAService라는 서비스(클래스)를 생성하지 않고 서비스를 사용할 컴포넌트의 생성자에 전 코드형식으로 작성하여 클래스를 생성할 필요없이 앵귤러에서 대신 클래스를 생성해서 제공하는 것을 의미한다.
말이 조금 어려울 수 있는데 쉽게 생각하면 일반적으로 클래스를 생성하는데 new ~ 를 쓰지않고 constructo를 이용해서 생성을하는 것이다. 해당 객체를 사용하는 방법은 .
을 이용하여 일반적으로 사용할 수 있다.
예제를 위해 변경한 ser-a.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class SerAService {
private num;
constructor() {
this.num = {
'a': '첫번째',
'b': '두번째'
};
}
methodA(number: String, code: string) {
const msg = this.num[code];
return `${msg}, ${number}`;
}
}
하지만 여기서 끝나는 것이 아니다. 마지막으로 해당 클래스를 의존성으로 주입할 것이라는 정보를 어딘가에 등록하는 것이다.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AComponent } from './a/a.component';
import { BComponent } from './b/b.component';
import { SerAService } from './ser-a.service';
@NgModule({
declarations: [
AppComponent,
AComponent,
BComponent
],
imports: [
BrowserModule
],
providers: [SerAService],
bootstrap: [AppComponent]
})
export class AppModule { }
providers라는 키를 추가하고 배열안에 생성할 클래스를 추가한다.
이렇게 작성할 경우 아무리 b를 입력해보아도 두번째라는 녀석은 출력되지 않는다. 왜냐하면 a.component.ts
파일의 this.number = this.serSupporter.methodA(this.number, 'a');
에서 'a'를 고정값으로 넘겨주기 때문이다. 'a'값을 변수로 지정해주고 해당값을 바인딩만 잘해주면 해결될 것이다.
'Front_End > Angular' 카테고리의 다른 글
05. Angular로 개발하기 - 3 - 구조 지시자 (0) | 2017.08.19 |
---|---|
03. Angular로 개발하기 - 1 - src/app, Component, Data Binding (0) | 2017.07.28 |
02. Angular 시작하기 (0) | 2017.07.08 |
01. Angular 준비하기 (0) | 2017.07.07 |
00. Angular의 개념/구조 (0) | 2017.07.03 |