목차

Service

Angularcomponent기반으로 작성하고자 한다. 소스는 독립성을 두어야 할 필요가 있다. 그중하나가 service라는 개념이다. service는 특별한 목적을 가지는 클래스이다. Injectable annotation을 사용하여 DI1)을 제공한다. - 데이타 공유 - 응용프로그램 로직 구현 - 외부 접속창구 역할

Sample

employee.service.ts
import { Injectable } from '@angular/core';
 
@Injectable({
   providedIn: 'root'
})
export class EmployeeService {
 
  constructor() { }
 
  getEmployees(){
    return [
      { id: 3, name: "둘리", age: 100030 },
      { id: 4, name: "고길동", age: 30 },
      { id: 5, name: "희동이", age: 30 },
      { id: 5, name: "고철수", age: 30 },
    ];
  }
}

HttpClient

HttpClient

employee.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { IEmployee } from './employee';
//import { Observable } from 'rxjs';
import { throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
 
@Injectable({
   providedIn: 'root'
})
export class EmployeeService {
  private _url: string = "/assets/data/employees.json"
 
  constructor(private http: HttpClient) { }
 
  getEmployees(): Observable<IEmployee[]>{
    return this.http.get<IEmployee[]>(this._url)
      .pipe(
        catchError(this.errorHandler)
      );
  }
  errorHandler(error: HttpErrorResponse){
    return throwError(error);
  }
}
1)
Dependency Injection