Skip to content

Instantly share code, notes, and snippets.

@PradeepLoganathan
Created May 19, 2018 11:52
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 PradeepLoganathan/002e8331efcd63e38d357183abd2a507 to your computer and use it in GitHub Desktop.
Save PradeepLoganathan/002e8331efcd63e38d357183abd2a507 to your computer and use it in GitHub Desktop.
Angular service to get a JWT token from the token endpoint
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