Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. @Injectable()
  2. export class AuthenticationService {
  3. public token: string;
  4. .......... your other codes.....................
  5. login(username: string, password: string): Observable<boolean> {
  6. return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
  7. .map((response: Response) => {
  8. // login successful if there's a jwt token in the response
  9. let token = response.json() && response.json().token;
  10. if (token) {
  11. // set token property
  12. this.token = token;
  13.  
  14. // store username and jwt token
  15. localStorage.setItem('usertoken', JSON.stringify({ username: username, token: token }));
  16.  
  17. // return true to indicate successful login
  18. return true;
  19. } else {
  20. // return false to indicate failed login
  21. return false;
  22. }
  23. });
  24. }
  25. ....................... your other codes.......................
  26. }
  27.  
  28. @Injectable()
  29. export class UserService {
  30. constructor(
  31. private http: Http,
  32. private authenticationService: AuthenticationService) {
  33. }
  34.  
  35. getUsers(): Observable<User[]> {
  36. // add authorization header with jwt token
  37. let headers = new Headers({ 'Authorization': 'Bearer ' + this.authenticationService.token });
  38. let options = new RequestOptions({ headers: headers });
  39.  
  40. // get users from api
  41. return this.http.get('/api/users', options)
  42. .map((response: Response) => response.json());
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement