Created
February 20, 2018 16:23
-
-
Save kmaida/a903ebd4887b485d2c75c723ae940448 to your computer and use it in GitHub Desktop.
MEAN RSVP API service with pipeable RxJS operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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