Skip to content

Instantly share code, notes, and snippets.

@4skinSkywalker
Last active March 28, 2019 15:24
Show Gist options
  • Select an option

  • Save 4skinSkywalker/afcfd31e9b4367cf138fcbbe45f05ced to your computer and use it in GitHub Desktop.

Select an option

Save 4skinSkywalker/afcfd31e9b4367cf138fcbbe45f05ced to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core'
import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { tap, catchError } from 'rxjs/operators'
import { throwError } from 'rxjs'
// import our custom classes
import { AppError } from '../common/app-error';
import { UnauthError } from '../common/unauth-error';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
login(credentials) {
return this.http.post('/api/authentication', credentials)
.pipe(
catchError(this.handleError),
tap(response => {
localStorage.setItem('token', response['token'])
})
)
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// Client-side or network error
} else {
// Unsuccessful response code
if (error.status === 401) {
return throwError( new UnauthError() ) // look here
}
}
return throwError( new AppError(error.error) ) // and here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment