Utilizing a HttpInterceptor is essential for adding my Bearer token to all calls made to my WebApi. The interceptor seamlessly functions with all basic service calls.
However, there is one specific instance where I must invoke 2 methods and utilize the results from both to construct a combined model. Despite attempting to nest the observables using MergeMap, ForkJoin, and FlatMap, none of these approaches seem to activate my HttpInterceptor...
A snippet of the interceptor code:
export class JwtInterceptor implements HttpInterceptor {
constructor(private userService: UserService) { }
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// logic for adding authorization header with jwt token if available
let currentUser = this.userService.getCurrentUser();
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
Description of the service calls:
public getPriceList(): Observable<CuttingGapPartPrice[]> {
const list = sessionStorage.getItem(this.listSessionKey);
if (list) {
return of(JSON.parse(list) as CuttingGapPartPrice[]);
}
return super.getClient()
.get(`/api/cutting-gap-part-prices`, { headers: super.getHeaders() })
.pipe(map(response => {
sessionStorage.setItem(this.listSessionKey, JSON.stringify(response));
return response ? response as CuttingGapPartPrice[] : new Array<CuttingGapPartPrice>();
}));
}
public getPowerList(): Observable<MotorPower[]> {
const list = sessionStorage.getItem(this.listSessionKey);
if (list) {
return of(JSON.parse(list) as MotorPower[]);
}
return super.getClient()
.get(`/api/motor-power`, { headers: super.getHeaders() })
.pipe(map(response => {
sessionStorage.setItem(this.listSessionKey, JSON.stringify(response));
return response ? response as MotorPower[] : new Array<MotorPower>();
}));
}
While each individual method performs flawlessly, their combination or nesting does not produce the expected outcome.
Nested Call utilizing MergeMap:
public getQuotationPrices(quotation: Quotation): Observable<QuotationPrices> {
return this.cuttingGapPartPriceService.getPriceList().pipe(mergeMap(prices => {
return this.motorPowerService.getPowerList().pipe(map(powers => {
var result = new QuotationPrices();
//Custom logic goes here
return result;
}));
}));
}
The issue I am facing bears similarity to that discussed in this thread, yet I am unable to comprehend how to resolve it.
Edit - Nested Call using ForkJoin:
public getQuotationPrices(quotation: Quotation): Observable<QuotationPrices> {
return forkJoin([this.cuttingGapPartPriceService.getPriceList(), this.motorPowerService.getPowerList()]).pipe(map(data => {
const prices = data[0];
const powers = data[1];
var result = new QuotationPrices();
//Further processing here
return result;
}));
}
View of network activity in Chrome's developer tools: https://i.sstatic.net/p2Yld.png