Answer the question
In order to leave comments, you need to log in
How to make additional functions with Anular Interceptor?
In general, I had a task to make a chain of requests. 1 after another. For example, by clicking on the "item" I make 3 requests ... (ZY api can not do it differently). When receiving data, I stuff these 3 widgets ... ... In general, I have a template function and looks like this ($target is Subject Rxjs):
httpGetTemplate(param_url?, target?, arrCheck?) {
const httpHandler = () => {
const $params = param_url;
const $target = target;
const options = {
headers: new HttpHeaders().set('Authorization', 'Bearer ' + localStorage.getItem('token'))
};
this.http.get(this.apiURL + $params, options).subscribe((_data: any) => {
if (arrCheck) {
const $data = _data.result;
if ($target === this.allCategories) {
this.allCategoriesCollection = $data;
} else if ($target === this.checkFirebaseConnection) {
this.checkFire = $data;
}
}
$target.next(_data.result);
}, _error => {
console.log(_error);
this.errorsHandler(_error, httpHandler);
});
};
httpHandler();
}
// src/app/auth/jwt.interceptor.ts
// ...
import 'rxjs/add/operator/do';
export class JwtInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
// redirect to the login route
// or show a modal
}
}
});
}
}
This is also a great spot to cache any failed requests. This comes in handy if we have token refreshing in place and we want to retry the requests once we have a new token.
// src/app/auth/auth.service.ts
import { HttpRequest } from '@angular/common/http';
// ...
export class AuthService {
cachedRequests: Array<HttpRequest<any>> = [];
public collectFailedRequest(request): void {
this.cachedRequests.push(request);
}
public retryFailedRequests(): void {
// retry the requests. this method can
// be called after the token is refreshed
}
}
// src/app/auth/jwt.interceptor.ts
// ...
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse {
if (err.status === 401) {
this.auth.collectFailedRequest(request);
}
}
});
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question