Encountered a peculiar issue in my Angular application where the HttpClient fails to communicate effectively with the Spring Controller. Despite configuring proper endpoints and methods in the Spring Controller, the Angular service using HttpClient doesn't trigger corresponding HTTP requests.
I've double-checked API URLs' correctness, ensured CORS configuration's accuracy, and scrutinized browser console for any error messages without spotting any call to the endpoint. All checks were conducted in incognito mode ruling out cache issues.
I welcome any insights, suggestions, or troubleshooting steps that can assist in effectively diagnosing and resolving this perplexing dilemma.
Controller:
@PreAuthorize("hasRole('" + Role.MANAGER_ROLE_NAME + "') or hasRole('" + Role.STORE_ROLE_NAME + "')")
@GetMapping(value = "{organizationId}")
public List<SapAsset> getAssets(@PathVariable final long organizationId) {
return sapAssetService.getStoreAssets(organizationId);
}
Angular:
import {Injectable} from '@angular/core';
import {SecureHttpClientService} from '../../core/services/secure-http-client.service';
import {Asset} from "../models/asset";
import {DateTimeFormatterService} from "../../core/services/date-time-formatter.service";
import {AlertService} from "../../core/services/alert.service";
@Injectable()
export class AssetService {
protected url = '/assets';
private readonly storeAssetsCacheKey = 'cachedStoreAssets';
private readonly dcAssetsCacheKey = 'cachedDcAssets';
constructor(private secureHttpClient: SecureHttpClientService, private dateTimeFormatterService: DateTimeFormatterService,
private alertService: AlertService) {
}
public getAssets(storeId: number): Promise<Asset[]> {
const cachedStoreAssets = this.getFromCache(this.storeAssetsCacheKey);
if (Array.isArray(cachedStoreAssets)) {
return Promise.resolve(cachedStoreAssets);
}
return this.secureHttpClient.get(this.url + '/' + storeId)
.then((response: Asset[]) => {
this.saveToCache(response, this.storeAssetsCacheKey);
return response;
})
.catch((error: any) => {
this.alertService.error("general.sap_error");
});
}
Angular rest wrapper:
import {Injectable} from '@angular/core';
import {HttpClientService} from './http-client.service';
import {HttpHeaders} from '@angular/common/http';
import {AuthService} from '../../authentication/services/auth.service';
@Injectable()
export class SecureHttpClientService {
apiUrl: string;
constructor(private httpClient: HttpClientService, private authService: AuthService) {
}
private createAuthHeader() {
const headers = new HttpHeaders({
Authorization: 'Bearer ' + this.authService.getToken(),
});
const options = {
headers
};
return options;
}
public get(url: string): any {
return this.httpClient.get(url, this.createAuthHeader());
}
Angular get service:
import {Injectable} from '@angular/core';
import {EnvironmentSpecificService} from './environment-specific.service';
import {EnvSpecific} from '../models/env-specific';
import {HttpClient} from '@angular/common/http';
import {PageLoadingService} from '../../../services/page-loading.service';
@Injectable()
export class HttpClientService {
apiUrl: string;
constructor(private http: HttpClient, private environmentSpecificService: EnvironmentSpecificService, private pageLoadingService: PageLoadingService) {
environmentSpecificService.subscribe(this, this.setApiUrl);
}
private setApiUrl(caller: any, es: EnvSpecific) {
const thisCaller = caller as HttpClientService;
caller.apiUrl = es.apiUrl;
}
public getApiUrl(url: string): string {
return this.apiUrl + url;
}
private extractBase64ImageData(response: Response): String {
return 'data:image/png;base64,' + response.text();
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error || '';
const err = JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(error);
return Promise.reject(errMsg);
}
public get(url: string, options?: any): any {
const promise = this.http.get(this.getApiUrl(url), options).toPromise();
this.pageLoadingService.addPromise(promise);
return promise.catch(this.handleError);
}
Place where it called from:
import {Component, NgZone, OnInit} from '@angular/core';
// Truncated for brevity...