Advertisement
root777

How to bring token and visit other pages after login? Angula

Mar 21st, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. I would like to log in pages with `token` from a backend server written in Django (JWT token), I finally got a 200 in `login router` according this [angular-7-jwt-authentication-example-tutorial][1], but after login, I don't know how to bring this token and visit other pages, add `currentUser` to recognize or import some files? Really stuck in this issue.
  2. Any advices will be highly appreciated.
  3.  
  4. Partial code of `auth.service.ts` as below:
  5.  
  6. import { Inject, Injectable } from '@angular/core';
  7. import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
  8. import { BehaviorSubject, Observable, throwError } from 'rxjs';
  9. import { Auth, User } from '../domain';
  10. import { map, switchMap } from 'rxjs/operators';
  11.  
  12. @Injectable({ providedIn: 'root' })
  13. export class AuthService {
  14. private currentUserSubject: BehaviorSubject<Auth>;
  15. public currentUser: Observable<Auth>;
  16.  
  17. constructor(
  18. private http: HttpClient,
  19. @Inject('BASE_CONFIG') private config: { uri: string }
  20. ) {
  21. this.currentUserSubject = new BehaviorSubject<Auth>(JSON.parse(localStorage.getItem('currentUser') || '{}'));
  22. this.currentUser = this.currentUserSubject.asObservable();
  23. }
  24.  
  25. public get currentUserValue(): Auth {
  26. return this.currentUserSubject.value;
  27. }
  28.  
  29. login(email: string, password: string): Observable<Auth> {
  30. return this.http.post<any>(`${this.config.uri}/users`, { email, password })
  31. .pipe(map(user => {
  32. // login successful if there's a jwt token in the response
  33. if (user && user.token) {
  34. // store user details and jwt token in local storage to keep user logged in between page refreshes
  35. localStorage.setItem('currentUser', JSON.stringify(user));
  36. this.currentUserSubject.next(user);
  37. }
  38.  
  39. return user;
  40. }));
  41. }
  42.  
  43. partial code of `project.service.ts` as below:
  44.  
  45. // GET /projects
  46. get(username: string): Observable<Project[]> {
  47. const uri = `${this.config.uri}/projects`;
  48. // const uri = `${this.config.uri}/project/`;
  49. const params = new HttpParams().set('members_like', username);
  50. return this.http.get<Project[]>(uri, {
  51. params: params,
  52. headers: this.headers
  53. });
  54. }
  55.  
  56. [1]: http://jasonwatmore.com/post/2018/11/16/angular-7-jwt-authentication-example-tutorial
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement