У меня есть проект, в котором у меня будет домашняя страница, сервис и страница, где вызываются запросы API. Я хочу взять строку из поля ввода и передать ее службе, чтобы использовать ее в качестве токена в аутентификации. Проблема в том, что при маршрутизации на другую страницу токен теряется.
Домашняя страница. html
<code> <div class="center">
<h1 id="title" class="title">Είσοδος</h1>
</div>
<div class="center">
<p class="sub-title">Εισάγετε το token σας </p>
</div>
<div class="center">
<label class="label" for="input-password">Token: </label>
<input nbInput
fullWidth type="text" (ngModel)="token" #passa>
</div>
<div class = "center">
<pre>
Είσοδος
Homepage.component.ts
import {Component, OnDestroy,OnInit} from '@angular/core';
import { ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { analyzeAndValidateNgModules } from '@angular/compiler';
import { ParkingService } from '../../../services/parking.service';
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
@Component({
selector: 'ngx-homepage',
styleUrls: ['./homepage.component.scss'],
templateUrl: './homepage.component.html',
providers: [ParkingService]
})
@Injectable()
export class HomepageComponent {
a:string;
constructor (public parkingService: ParkingService, public root:Router) {
}
pass(passa)
{
this.a= passa.value;
window.alert(this.a);
this.parkingService.setUserToken(this.a);
this.root.navigate(['/pages/iot-dashboard']);
}
Service.ts
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 {HomeComponent} from '../pages/dashboard/homepage/homepage.component';
@Injectable()
export class ParkingService{
public userToken$: Subject<string> = new BehaviorSubject<string>(null);
public token: string;
constructor( private httpclient: HttpClient){
this.userToken$.subscribe( token => {
this.token = token;
console.log(this.token);
});
}
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));
}
errorHandler(error: any) {
if (error == 404)
return Observable.throw(error || "Please provide proper credentials");
}
addparkingDetails(parkingSite: any): Observable<any>{
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer: ' + this.token,
}),
};
return this.httpclient.post<any>(
"https://socialpark.iti.gr:8005/parking_sites/management/updates",
parkingSite,
httpOptions).pipe(
catchError(this.errorHandlerup));
}
errorHandlerup(error: any) {
if (error == 422){
return Observable.throw(error || "Duplicate licence plate found during insertion.");
}
else if (error == 401) {
return Observable.throw(error || "Please provide proper credentials");
}
}
}
dashboard.component.ts
import {Component, OnDestroy, ErrorHandler, OnInit} from
'@angular/core';
import { NbThemeService } from '@nebular/theme';
import { takeWhile } from 'rxjs/operators' ;
import { SolarData } from '../../@core/data/solar';
import {ParkingService} from '../../services/parking.service';
import { Router } from '@angular/router';
import { stringify } from 'querystring';
import { Subject, BehaviorSubject } from 'rxjs';
interface CardSettings {
title: string;
iconClass: string;
type: string;
}
@Component({
selector: 'ngx-dashboard',
styleUrls: ['./dashboard.component.scss'],
templateUrl: './dashboard.component.html',
providers: [ParkingService]
})
export class DashboardComponent implements OnDestroy,OnInit {
selectedMoments1 = new Date();
selectedMoments2 = new Date();
selectedMoment = new Date();
time1 = new Date();
time3 = new Date();
getdata: any;
parkingid: string;
parkingpost: any;
allspots: any;
getdatadis: any;
allspotsdis: any;
constructor(private parkingService: ParkingService, private router: Router,) {
}
ngOnInit(){
this.parkingService.getparkingDetails().subscribe(
data=>
{
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 => {
console.error(error);
},
);
}
plus(t1,t2,selected,a){
let plate:string = a.value;
const a1 = t1.value.slice(0,2);
const b1 = parseInt(a1);
const a2=t2.value.slice(0,2);
const b2 = parseInt(a2);
if(selected=="general"){
for (let index: number= b1; index <=b2; index++) {
this.parkingService.getparkingDetails().subscribe(
data=>
{
//this.getdata = 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)
this.parkingid = data._id
this.parkingpost={
"parking_site_id": this.parkingid,
"licence_plate": plate ,
"indexes": [index],
"operation_type":"append",
"spot_type": "conventional"
}
//this.parkingpost=JSON.parse(JSON.stringify(this.parkingpost));
this.parkingService.addparkingDetails(this.parkingpost).subscribe(
response => {
//this.router.navigate(['/pages/dashboard']);
window.alert("Επιτυχής ανανέωση στοιχείων");
setTimeout(() => {
this.parkingService.getparkingDetails().subscribe(
data=>
{
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 => {
console.error(error);
},
);
}, 3000);
},
error => {
console.error(error);
},
);
},
error => alert(error)
);
}
}
else{
for (let index: number= b1; index <=b2; index++) {
this.parkingService.getparkingDetails().subscribe(
data=>
{
this.getdata = data.spaces_occupied_current_slot.conventional
this.parkingid = data._id
this.parkingpost={
"parking_site_id": this.parkingid,
"licence_plate": plate ,
"indexes": [index],
"operation_type":"append",
"spot_type": "disabled"
}
//this.parkingpost=JSON.parse(JSON.stringify(this.parkingpost));
this.parkingService.addparkingDetails(this.parkingpost).subscribe(
response => {
//this.router.navigate(['/pages/dashboard']);
window.alert("Επιτυχής ανανέωση στοιχείων");
setTimeout(() => {
this.parkingService.getparkingDetails().subscribe(
data=>
{
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 => {
console.error(error);
},
);
}, 2000);
},
error => {
console.error(error);
},
);
},
error => alert(error)
);
}
}
}
plin(t3,selected2,b)
{
const plate = b.value;
const a3=t3.value.slice(0,2);
const b3 = parseInt(a3);
window.alert(b3);
window.alert(plate);
if(selected2=="general"){
this.parkingService.getparkingDetails().subscribe(
data=>
{
this.getdata = data.spaces_occupied_current_slot.conventional
this.parkingid = data._id
this.parkingpost={
"parking_site_id": this.parkingid,
"licence_plate": plate ,
"indexes": [b3],
"operation_type":"remove",
"spot_type": "conventional"
}
//this.parkingpost=JSON.parse(JSON.stringify(this.parkingpost));
this.parkingService.addparkingDetails(this.parkingpost).subscribe(
response => {
//this.router.navigate(['/pages/dashboard']);
window.alert("Επιτυχής ανανέωση στοιχείων");
setTimeout(() => {
this.parkingService.getparkingDetails().subscribe(
data=>
{
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 => {
console.error(error);
},
);
}, 2000);
},
error => {
console.error(error);
},
);
},
error => alert(error)
);
}
else{
this.parkingService.getparkingDetails().subscribe(
data=>
{
this.getdata = data.spaces_occupied_current_slot.conventional
this.parkingid = data._id
this.parkingpost={
"parking_site_id": this.parkingid,
"licence_plate": plate ,
"indexes": [b3],
"operation_type":"remove",
"spot_type": "disabled"
}
//this.parkingpost=JSON.parse(JSON.stringify(this.parkingpost));
this.parkingService.addparkingDetails(this.parkingpost).subscribe(
response => {
//this.router.navigate(['/pages/dashboard']);
window.alert("Επιτυχής ανανέωση στοιχείων");
setTimeout(() => {
this.parkingService.getparkingDetails().subscribe(
data=>
{
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 => {
console.error(error);
},
);
}, 2000);
},
error => {
console.error(error);
},
);
},
error => alert(error)
);
// new_conv = p.spaces_occupided.disabled[b3].remove(plate);
//service.post(new_conv);
}
}
private alive = true;
//constructor(private themeService: NbThemeService,
// private solarService: SolarData) {
//this.themeService.getJsTheme()
// .pipe(takeWhile(() => this.alive))
//.subscribe(theme => {
//this.statusCards = this.statusCardsByThemes[theme.name];
//});
//this.solarService.getSolarData()
//.pipe(takeWhile(() => this.alive))
//.subscribe((data) => {
//this.solarValue = data;
// });
//}
ngOnDestroy() {
this.alive = false;
}
}
console.log (this.token) в конструкторе печатает 'null', токен и затем снова null
Как вы можете видеть здесь