목차

HTTP and Observables

Observables

A sequence of items that arrive asynchronously over time. HTTP call - single item Single item - HTTP response

HTTP, Observables and RxJS

  1. HTTP Get request from EmpService
  2. Receive the observable and cast it into an employee array
  3. Subscribe to the observable from EmpList and EmpDetail
  4. Assign the employee array to a local variable

RxJS

employee.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { IEmployee } from './employee';
import { Observable } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
 
// @Injectable({
//   providedIn: 'root'
// })
@Injectable()
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 Observable.throw(error.message || "Server Error");
  }
}