Как сохранить токен, когда я обновляю sh свою страницу в Angular2? - PullRequest
0 голосов
/ 19 июня 2020

У меня есть домашняя страница, где кто-то вставляет токен, а затем переходит на главную страницу, а затем на вторую страницу с помощью кнопки. Я использую службу для передачи токена между тремя компонентами и службу, в которой я вызываю запросы API с этим токеном. Когда я нахожусь на главной или второй странице и обновляю sh страницу, токен теряется. Что делать?

компонент домашней страницы

export class HomepageComponent implements OnInit {

    token:any;
    a:string;
  settings: any;
  constructor (public parkingService: ParkingService, public root:Router, public dataService:DataService) { 


  }
  ngOnInit(){


  }

        pass(passa)
          {

        this.a= passa.value;
        this.parkingService.setUserToken(this.a);

       // this.dataService.token=this.a;
         var token = this.a;
        localStorage.setItem("token", token);

        this.dataService.setToken(localStorage.getItem("token"));
        this.parkingService.getparkingDetails().subscribe(
          data=>
          {
           // this.dataService.token=this.a;
        this.root.navigate(['/pages/iot-dashboard']);

      },
      error => {
        window.alert("Παρακαλώ δώστε έγκυρο token για το χώρο στάθμευσης");
        console.error(error);
        this.root.navigate(['/pages/dashboard'] );

      },
      );
          }




}

компонент главной страницы

export class DashboardComponent implements OnInit {



  selectedMoments1 = new Date();
  selectedMoments2 = new Date();
  selectedMoment = new Date();
  time1 = new Date();
  time2 = new Date();
  time3 = new Date();
  getdata: any;
  parkingid: string;
  parkingpost: any;
  allspots: any;
  getdatadis: any;
  allspotsdis: any;
 // token:string;
  snapshot:any;
  selected="general";
  selected2="general";

  token:any;
  listadis:string[];
  plate:any;
  listindexdisabled:number[]=[];
  listindex:number[]=[];
  user:any;
  constructor(private parkingService: ParkingService, private route:ActivatedRoute, public root:Router , public dataservice:DataService) {


  }
  ngOnInit(){
    this.token=this.dataservice.token;
    //this.dataservice.setToken(this.token);
    this.parkingService.setUserToken(this.token);
    this.parkingService.getparkingDetails().subscribe(
      data=>
      {
      this.parkingid = data._id
      this.getdata = JSON.parse(data.spaces_occupied_current_slot.conventional)
      this.allspots = JSON.parse(data.space_total.conventional)
      this.getdatadis = JSON.parse(data.spaces_occupied_current_slot.disabled)
      this.allspotsdis = JSON.parse(data.space_total.disabled)
    },
    error => {
      window.alert("Παρακαλώ δώστε έγκυρο token για το χώρο στάθμευσης");
      console.error(error);
      this.root.navigate(['/pages/dashboard']);

    },
    );

  }
........

сервис для передачи токена между компонентами

import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Injectable()
export class DataService {

     public token: string;

     setToken(token:any){
          this.token=token;


       }

}

сервис для запросов API с токеном

import {Component, OnDestroy, ErrorHandler, OnInit} from '@angular/core';
import { Injectable } from '@angular/core';
import {
    BehaviorSubject,
    Observable,
    throwError as observableThrowError,
    Subject,
  } from 'rxjs';

  import {
    HttpClient,
    HttpErrorResponse,
    HttpHeaders,
  } from '@angular/common/http';
  import 'rxjs/add/operator/map';
  import { catchError} from 'rxjs/operators';
import { NbAuthSimpleToken, NbAuthService, NbAuthSimpleInterceptor } from '@nebular/auth';
import { Router } from '@angular/router';
import {DataService} from './data.service';


@Injectable()
  export class ParkingService implements OnInit{
    public userToken$: Subject<string> = new BehaviorSubject<string>(null);
     public token: string;

    currenttoken = this.userToken$.asObservable();

    constructor( private httpclient: HttpClient, private root:Router, private dataservice:DataService){
      this.userToken$.subscribe( token => {
        this.token = token;
        console.log(this.token)

  });
      this.dataservice.token

    }
  ngOnInit(): void {


  }

    setUserToken(token: string) {

      this.userToken$.next(token);


  }

      getparkingDetails(): Observable<any>{

        console.log(this.token);
        const httpOptions = {


            headers: new HttpHeaders({

              'Content-Type':  'application/json',
              'Authorization': 'Bearer: ' + this.token,
            }),
          };


          return this.httpclient.get<any>("https://socialpark.iti.gr:8005/parking_sites/management", httpOptions).pipe(
            catchError(this.errorHandler));
        }  

Ответы [ 2 ]

0 голосов
/ 22 июня 2020

При успешном входе в систему вы можете сохранить токен в локальном хранилище, как указано здесь

login(userObj:User) {
    return this.http.post<any>(`${config.apiUrl}/users/login`, userObj)
        .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('user', JSON.stringify(user));
            }

            return user;
        }));
}

токен не будет удален при обновлении браузера sh или закрыт, пока пользователь не удалит его вручную, следовательно,

  logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('user');
}

Получите сохраненный токен из локального хранилища в вашем компоненте, как показано ниже

import { Component, OnInit } from '@angular/core';

@Component({templateUrl: 'home.component.html'})
export class HomeComponent implements OnInit {
    currentUser: User;

    constructor() {
        this.currentUser = JSON.parse(localStorage.getItem('user'));
    }

    ngOnInit() {
    }

   }

Кроме того, вы можете добавить этот токен к каждому HTTP-запросу с помощью JWT Interceptor

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        let currentUser = JSON.parse(localStorage.getItem('user'));
        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: { 
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
        }

        return next.handle(request);
    }
}

Добавить перехватчик в массив провайдеров app.module

   import { JwtInterceptor} from './_helpers';

    @NgModule({
    imports: [ .. ],
    declarations: [..],
    providers: [
     { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    ]
    })
0 голосов
/ 19 июня 2020

как насчет сохранения токена в localstorage?

#Set
localStorage.setItem("token", "xyz");

#get
localStorage.getItem("token", "xyz");

edit 1 --- вы можете установить это в классе обслуживания

export class DataService {

     public token: string;

     public DataService(){
        this.token = localStorage.getItem("token");
     }

     setToken(token:any){
        this.token=token;
        localStorage.setItem("token", token);

       }

}
...