In the process of creating a simple interceptor, I have encountered an issue. The interceptor is designed to check if an outgoing request is targeting a specific endpoint type, namely events
and favoriteevents
.
While the interceptor works almost as intended, there is one issue that needs to be addressed. Currently, the this.dispatcher
dispatches before the outgoing request is completed.
How can I modify the code so that the outgoing request executes first, followed by the dispatch call?
import {Injectable, Injector, Optional} from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {AppConstants} from '@constants/app-constants.constant';
import {DispatcherService} from '@services/dispatcher.service';
@Injectable()
export class EventsInterceptor implements HttpInterceptor {
constructor(private dispatcher: DispatcherService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const urls = [
{requestType: 'PUT', snippet: '/events/'},
{requestType: 'DELETE', snippet: '/events/'},
{requestType: 'PUT', snippet: '/favoriteevents'},
{requestType: 'DELETE', snippet: '/favoriteevents'}
];
for (const url of urls) {
if (req.method === url.requestType || url.requestType === null) {
if (req.url.indexOf(url.snippet) !== -1) {
this.dispatcher.dispatch({type: AppConstants.actions.refreshFavoriteEvents});
}
}
}
return next.handle(req);
}
}