Advertisement
Guest User

Untitled

a guest
Sep 14th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. @Component({
  2. selector: 'login',
  3. templateUrl: 'app/views/login.html',
  4. providers: [ LoginService ],
  5. styleUrls: [ 'css/login.css' ]
  6. })
  7. export class Login {
  8. postData: string;
  9.  
  10. constructor(private _loginService: LoginService) {}
  11.  
  12. onLogin(user : string, password: string) {
  13. if (!user && !password){return;}
  14. this._loginService.login(user , password)
  15. .subscribe (
  16. data => this.postData = JSON.stringify({user : user , password: password}),
  17. error => alert(error),
  18. () => console.log(this.postData)
  19. );
  20. }
  21. }
  22.  
  23. <label for="user">User</label>
  24. <input type="text" id="user" #user>
  25. <label for="password">Password</label>
  26. <input type="password" id="password" #password>
  27. <button type="submit" (click)="onLogin(user.value, password.value); user.value=''; password.value=''">Login</button>
  28.  
  29. @Injectable()
  30. export class LoginService {
  31. constructor (private _http: Http){}
  32.  
  33. private loginUrl = './users';
  34.  
  35. login(user: string, password: string): Observable<User> {
  36. let body = JSON.stringify({"user": user, "password": password});
  37. let headers = new Headers({'Content-Type': 'application/json'});
  38. let options = new RequestOptions({headers: headers});
  39.  
  40. return this._http.post(this.loginUrl, body, options)
  41. .map(this.extractData)
  42. .catch(this.handleError);
  43. }
  44.  
  45. private extractData(res: Response) {
  46. let body = res.json();
  47. return body.data || { };
  48. }
  49.  
  50. private handleError (error: any) {
  51. // In a real world app, we might use a remote logging infrastructure
  52. // We'd also dig deeper into the error to get a better message
  53. let errMsg = (error.message) ? error.message :
  54. error.status ? `${error.status} - ${error.statusText}` : 'Server error';
  55. console.error(errMsg); // log to console instead
  56. return Observable.throw(errMsg);
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement