Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- Any advices will be highly appreciated.
- Partial code of `auth.service.ts` as below:
- import { Inject, Injectable } from '@angular/core';
- import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
- import { BehaviorSubject, Observable, throwError } from 'rxjs';
- import { Auth, User } from '../domain';
- import { map, switchMap } from 'rxjs/operators';
- @Injectable({ providedIn: 'root' })
- export class AuthService {
- private currentUserSubject: BehaviorSubject<Auth>;
- public currentUser: Observable<Auth>;
- constructor(
- private http: HttpClient,
- @Inject('BASE_CONFIG') private config: { uri: string }
- ) {
- this.currentUserSubject = new BehaviorSubject<Auth>(JSON.parse(localStorage.getItem('currentUser') || '{}'));
- this.currentUser = this.currentUserSubject.asObservable();
- }
- public get currentUserValue(): Auth {
- return this.currentUserSubject.value;
- }
- login(email: string, password: string): Observable<Auth> {
- return this.http.post<any>(`${this.config.uri}/users`, { email, password })
- .pipe(map(user => {
- // login successful if there's a jwt token in the response
- if (user && user.token) {
- // store user details and jwt token in local storage to keep user logged in between page refreshes
- localStorage.setItem('currentUser', JSON.stringify(user));
- this.currentUserSubject.next(user);
- }
- return user;
- }));
- }
- partial code of `project.service.ts` as below:
- // GET /projects
- get(username: string): Observable<Project[]> {
- const uri = `${this.config.uri}/projects`;
- // const uri = `${this.config.uri}/project/`;
- const params = new HttpParams().set('members_like', username);
- return this.http.get<Project[]>(uri, {
- params: params,
- headers: this.headers
- });
- }
- [1]: http://jasonwatmore.com/post/2018/11/16/angular-7-jwt-authentication-example-tutorial
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement