recently, the project has been developing with angular6, encapsulating an interceptor for HttpInterceptor, but has been reporting errors.
< H2 > Code in auth.service.ts < / H2 >import {Injectable} from "@angular/core";
import {HttpService} from "./services/http.service";
@Injectable()
export class AuthService {
public timestamp: any = "";
constructor(private http: HttpService) {
}
/*
*
* */
getTimestamp() {
this.http.getData("/common/timestamp").subscribe((respData: any) => {
if (respData.code === "0000") {
this.timestamp = respData.data;
}
}
);
}
//test
getAuthorizationToken() {
return "some-auth-token";
}
}
< hr >
< H2 > interceptor.service.ts < / H2 >
import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from "@angular/common/http";
import {Observable} from "rxjs";
import {tap} from "rxjs/operators";
import {constant} from "../../providers";
import {AuthService} from "../auth.service";
@Injectable()
export class InterceptorService implements HttpInterceptor {
constructor(private authService: AuthService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// const authToken = this.authService.getTimestamp(); //
const authToken = this.authService.getAuthorizationToken();
const clonedRequest = req.clone({
setHeaders: {
leo: "test",
version: constant.VERSIONS,
},
});
console.log(clonedRequest.method);
return next.handle(clonedRequest).pipe(
tap(
event => {
if (event instanceof HttpResponse) {
console.log(event);
}
},
error => {
console.error(error.message);
}
)
);
}
}
if I release const authToken = this.authService.getTimestamp (); in interceptor.service.ts, I will fall into a loop.
I want to add a timestamp to the header request header of the interceptor for verification. This timestamp must be retrieved from the backend when the post request is made. Now I don"t know how to solve it. Does anyone know? Thank you