Angula HttpClient - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki

HttpClientModule Angular HTTPClient

Verbs:

  • get
  • post
  • put
  • delete
  • patch
  • head
  • jsonp

get("URL"): Observable

Error: HttpErrorResponse

Observable:

Transform Data

map

Retry

retry

Options

  • HttpParams: URL params
  • HttpHeaders: request header

Interceptors

  • Request Interceptor:
@Injectable()
export class GithubAPIInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    // if it is a Github API request
    if (req.url.includes('api.github.com')) {
      // we need to add an OAUTH token as a header to access the Github API
      const clone = req.clone({ setHeaders: { 'Authorization': `token ${OAUTH_TOKEN}` } });
      return next.handle(clone);
    }
    // if it's not a Github API request, we just handle it to the next handler
    return next.handle(req);
  }
}
  • Response Interceptors:
@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
  constructor(private router: Router, private errorHandler: ErrorHandler) {}
  
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
    // we catch the error
    .catch((errorResponse: HttpErrorResponse) => {
      // if the status is Unauthorized
      if (errorResponse.status === 401) {
        // we redirect to login
        this.router.navigateByUrl('/login');
      } else {
        // else we notify the user
        this.errorHandler.handle(errorResponse);
      }
      return Observable.throw(errorResponse);
    });
  }
}

Test - HttpClientTestingModule, HttpTestingController

describe('RaceService', () => {
  let raceService: RaceService;
  let http: HttpTestingController;

  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [RaceService]
  }));

  beforeEach(() => {
    raceService = TestBed.get(RaceService);
    http = TestBed.get(HttpTestingController);
  });

  it('should return an Observable of 2 races', async(() => {
    // fake response
    const hardcodedRaces = [{ name: 'London' }, { name: 'Lyon' }];
    // call the service
    let actualRaces = [];
    raceService.list().subscribe(races => actualRaces = races);

    // check that the underlying HTTP request was correct
    http.expectOne('/api/races')
      // return the fake response when we receive a request
      .flush(hardcodedRaces);

    // check that the returned array is deserialized as expected
    expect(actualRaces.length).toBe(2);
  }));
});
⚠️ **GitHub.com Fallback** ⚠️