Използвам Ionic 4, за да създам приложение. Опитвам се да внедря HttpInterceptor, за да добавя токена за оторизация на носителя към заявките.
Проблем: заявката се изпраща преди токенът да бъде прочетен
Повече информация:
- Опитвам се да прочета токена от локално хранилище
- console.log по-долу отпечатва токена
Какво не е наред ?
import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpResponse,HttpErrorResponse} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
token:any;
constructor(private router: Router,private storage: Storage) {
this.storage.get('User').then((val) => {
this.token = val;
console.log(val); // Returns the token
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(this.token); // Returns undefined
if (this.token) {
request = request.clone({
setHeaders: {
'Authorization': this.token
}
});
}
if (!request.headers.has('Content-Type')) {
request = request.clone({
setHeaders: {
'content-type': 'application/json'
}
});
}
request = request.clone({
headers: request.headers.set('Accept', 'application/json')
});
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log('event--->>>', event);
}
return event;
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
if (error.error.success === false) {
// this.presentToast('Login failed');
} else {
this.router.navigate(['/']);
}
}
return throwError(error);
}));
}
}