Created
May 19, 2018 11:52
-
-
Save PradeepLoganathan/002e8331efcd63e38d357183abd2a507 to your computer and use it in GitHub Desktop.
Angular service to get a JWT token from the token endpoint
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 { OnInit, Injectable } from "@angular/core"; | |
import { Observable } from "rxjs/Observable"; | |
import { | |
HttpClient, | |
HttpHeaders, | |
HttpErrorResponse | |
} from "@angular/common/http"; | |
import { environment } from "../../../../environments/environment"; | |
import { tap, catchError } from "rxjs/operators"; | |
import { ErrorObservable } from "rxjs/observable/ErrorObservable"; | |
@Injectable() | |
export class TokenizerService implements OnInit { | |
ngOnInit(): void {} | |
constructor(private http: HttpClient) {} | |
getToken(): Observable<any> { | |
const headers = new HttpHeaders({ "Content-Type": "application/json" }); | |
const url = `${environment.tokenapi}`; | |
return this.http | |
.post( | |
url, | |
{ userName: "username", password: "password" }, | |
{ headers: headers } | |
) | |
.pipe( | |
tap(data => console.log("Data: " + JSON.stringify(data))), | |
catchError(this.handleError) | |
); | |
} | |
private handleError(err: HttpErrorResponse): ErrorObservable { | |
let errorMessage: string; | |
if (err.error instanceof Error) { | |
// A client-side or network error occurred. Handle it accordingly. | |
errorMessage = `An error occured: ${err.error.message}`; | |
} else { | |
// The backend returned an unsuccessful response code. | |
// The response body may contain clues as to what went wrong, | |
errorMessage = `Backend returned code ${err.status}, body was: ${ | |
err.error | |
}`; | |
} | |
console.error(err); | |
return new ErrorObservable(errorMessage); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment