Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. export class LoginComponent implements OnInit{
  2. model: any = {};
  3. loading = false;
  4.  
  5. constructor(
  6. private router: Router,
  7. private authenticationService: AuthenticationService,
  8. private alertService: AlertService
  9. ){}
  10.  
  11. ngOnInit(){
  12. // reset login status
  13. this.authenticationService.logout();
  14. }
  15.  
  16. login(){
  17. let errMsg: string;
  18. this.loading = true;
  19. this.authenticationService.login(this.model.username, this.model.password)
  20. .subscribe(
  21. data => {
  22. console.log('Success');
  23. //this.router.navigate(['/']);
  24. },
  25. error => {
  26. console.log('Error');
  27. this.loading = false;
  28. }
  29. );
  30. }
  31.  
  32. export class AuthenticationService{
  33.  
  34. private baseUrl = '..';
  35.  
  36. constructor(private http: Http){}
  37.  
  38. login(username: string, password: string): Observable<Response>{
  39. let body = JSON.stringify({username: username, password: password});
  40. let headers = new Headers({ 'Content-Type': 'application/json' });
  41. let options = new RequestOptions({ headers: headers});
  42. const url = `${this.baseUrl}/api/auth/login`;
  43.  
  44. return this.http.post(url, body, options)
  45. .map(this.extractData)
  46. .catch(this.handleError);
  47.  
  48. }
  49.  
  50. logout(){
  51. // remove user from local storage to log user out
  52. localStorage.removeItem('currentUser');
  53. }
  54.  
  55. private extractData(res: Response) {
  56. let body = res.json();
  57. return body.data || { };
  58. }
  59.  
  60. private handleError (error: Response | any) {
  61. // In a real world app, we might use a remote logging infrastructure
  62. let errMsg: string;
  63. if (error instanceof Response) {
  64. const body = error.json() || '';
  65. const err = body.error || JSON.stringify(body);
  66. errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  67. } else {
  68. errMsg = error.message ? error.message : error.toString();
  69. }
  70. console.error(errMsg);
  71. return Observable.throw(errMsg);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement