Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. @Injectable()
  2. export class AuthService {
  3. private url ='http://localhost:3000/user/1';
  4. constructor(private http: Http){}
  5. isLoggedIn: boolean = false;
  6. user : User;
  7. errorMessage:any;
  8.  
  9.  
  10. login(username:string, password:string) {
  11. this.getUser(username, password).subscribe((user)=>{
  12. if(user.login===username && password===user.password){
  13. this.isLoggedIn=true;
  14. }
  15. })
  16. }
  17.  
  18. logout(): void {
  19. this.isLoggedIn = false;
  20. }
  21.  
  22. getUser(username:string, password:string): Observable<User>{
  23. return (this.http.get(this.url)
  24. .map(this.extractData)
  25. .catch(this.handleError))
  26.  
  27. }
  28.  
  29. private extractData(res: Response){
  30. let body = res.json();
  31. return body || {};
  32. }
  33.  
  34. private handleError (error: Response | any) {
  35. // In a real world app, you might use a remote logging infrastructure
  36. let errMsg: string;
  37. if (error instanceof Response) {
  38. const body = error.json() || '';
  39. const err = body.error || JSON.stringify(body);
  40. errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  41. } else {
  42. errMsg = error.message ? error.message : error.toString();
  43. }
  44. console.error(errMsg);
  45. return Observable.throw(errMsg);
  46. }
  47. }
  48.  
  49. public Dologin() {
  50. this.message = 'Trying to log in ...';
  51.  
  52. this.authService.login(this.model.username, this.model.password)
  53. .subscribe(() => {
  54. this.setMessage();
  55. if (this.authService.isLoggedIn) {
  56.  
  57. let redirect = '/main';
  58.  
  59. let navigationExtras: NavigationExtras = {
  60. preserveQueryParams: true,
  61. preserveFragment: true
  62. };
  63.  
  64. // Redirect the user
  65. this.router.navigate([redirect], navigationExtras);
  66. }
  67. });
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement