Skip to content

Instantly share code, notes, and snippets.

@kmaida
Created February 20, 2018 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmaida/a903ebd4887b485d2c75c723ae940448 to your computer and use it in GitHub Desktop.
Save kmaida/a903ebd4887b485d2c75c723ae940448 to your computer and use it in GitHub Desktop.
MEAN RSVP API service with pipeable RxJS operators
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { AuthService } from './../auth/auth.service';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import 'rxjs/add/observable/throw';
import { ENV } from './env.config';
import { EventModel } from './models/event.model';
import { RsvpModel } from './models/rsvp.model';
@Injectable()
export class ApiService {
constructor(
private http: HttpClient,
private auth: AuthService) { }
...
// GET list of public, future events
getEvents$(): Observable<EventModel[]> {
return this.http
.get(`${ENV.BASE_API}events`)
.pipe(
catchError((error, caught) => this._handleError(error, caught))
);
}
...
// Handle errors
private _handleError(err, caught): Observable<any> {
const errorMsg = err.message || 'Error: Unable to complete request.';
if (err.message && err.message.indexOf('No JWT present') > -1) {
this.auth.login();
}
return Observable.throw(errorMsg);
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment