Create a class InterceptService
to intercept http requests,
// Angular
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest,
HttpResponse } from '@angular/common/http';
// RxJS
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { debug } from 'util';
import {ToastrService} from 'ngx-toastr';
import {LoadingService} from '../../../../views/pages/_services/loading.service';
@Injectable()
export class InterceptService implements HttpInterceptor {
constructor(private toast: ToastrService,private loadingService: LoadingService){}
// intercept request and add token
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
// tslint:disable-next-line:no-debugger
// modify request
// request = request.clone({
// setHeaders: {
// Authorization: `Bearer ${localStorage.getItem('accessToken')}`
// }
// });
// console.log('----request----');
// console.log(request);
// console.log('--- end of request---');
return next.handle(request).pipe(
tap(
event => {
if (event instanceof HttpResponse) {
// console.log('all looks good');
// http response status code
// console.log(event.status);
}
},
error => {
this.toast.error(error.message,error.status);
this.loadingService.waitLoadingClose();
// http response status code
// console.log('----response----');
// console.error('status code:');
// tslint:disable-next-line:no-debugger
//console.error(error.status);
//console.error(error.message);
// console.log('--- end of response---');
}
)
);
}
}
add the line below in your Module:
providers: [
InterceptService,
{
provide: HTTP_INTERCEPTORS,
useClass: InterceptService,
multi: true
},
],
in his own class InterceptService
Voce can take the headers
Voce q has backend control?
– rafaelphp
@rafaelphp Yes, I have
– SanOli
Then return the token to body and not headers so Oce can pick up the token and save it to your front end and then send the token to the url you need. headers("Authorization Baer token")
– rafaelphp
Voce tmb can create an Intercept and add to your app, so Voce can better handle data requirements
– rafaelphp
@rafaelphp I asked the architect responsible for the API to return the token in body, it turns out I need to implement this hj yet, and it’s an update that we won’t be able to do for now. There is some way to do this by the same header?
– SanOli
create an Intercept class watch this video https://www.youtube.com/watch?v=vHoNOpfDdNQ
– rafaelphp
but he probably has to create via body, because I never used any api that in header and always via body, asks him to see about JWT https://jwt.io/introduction/
– rafaelphp