Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export class LoginComponent implements OnInit{
- model: any = {};
- loading = false;
- constructor(
- private router: Router,
- private authenticationService: AuthenticationService,
- private alertService: AlertService
- ){}
- ngOnInit(){
- // reset login status
- this.authenticationService.logout();
- }
- login(){
- let errMsg: string;
- this.loading = true;
- this.authenticationService.login(this.model.username, this.model.password)
- .subscribe(
- data => {
- console.log('Success');
- //this.router.navigate(['/']);
- },
- error => {
- console.log('Error');
- this.loading = false;
- }
- );
- }
- export class AuthenticationService{
- private baseUrl = '..';
- constructor(private http: Http){}
- login(username: string, password: string): Observable<Response>{
- let body = JSON.stringify({username: username, password: password});
- let headers = new Headers({ 'Content-Type': 'application/json' });
- let options = new RequestOptions({ headers: headers});
- const url = `${this.baseUrl}/api/auth/login`;
- return this.http.post(url, body, options)
- .map(this.extractData)
- .catch(this.handleError);
- }
- logout(){
- // remove user from local storage to log user out
- localStorage.removeItem('currentUser');
- }
- private extractData(res: Response) {
- let body = res.json();
- return body.data || { };
- }
- private handleError (error: Response | any) {
- // In a real world app, we might use a remote logging infrastructure
- let errMsg: string;
- if (error instanceof Response) {
- const body = error.json() || '';
- const err = body.error || JSON.stringify(body);
- errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
- } else {
- errMsg = error.message ? error.message : error.toString();
- }
- console.error(errMsg);
- return Observable.throw(errMsg);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement