Angular HTTP client fails to communicate with Spring controller

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...

Answer №1

One important step you missed is subscribing to your observable. Remember, the Angular HttpClient's get() method returns an observable, not a Promise.

To rectify this, make sure to include .subscribe() immediately after the closing parentheses and everything should work smoothly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instruct the main component to retrieve updated information

Within my parent component, there is a router outlet containing a component that generates new objects associated with the parent. I'm unsure how to notify the parent component to make a new API call for updated data. Can you assist me in understandin ...

When using the map function, I am receiving an empty item instead of the intended item based on a condition

Need assistance with my Reducer in ngRx. I am trying to create a single item from an item matching an if condition, but only getting an empty item. Can someone please help me out? This is the code for the Reducer: on(rawSignalsActions.changeRangeSchema, ...

Effective techniques to resolve selenium error in Java when using JFrame

I recently developed an application using java, selenium, and JFrame. However, when attempting to launch it in a JNLP page, I encountered the following error: java.security.AccessControlException: access denied ("java.util.PropertyPermission" "com.google. ...

Is it possible for Java Applets to interact with external sources with user consent?

My goal is to develop a platform where users can input external websites, and my application will modify the returned source before providing it back to the user. The challenge lies in the fact that HTML5 and flash sockets have limitations when it comes to ...

There is no correlationId found within the realm of node.js

Currently, I am in the process of implementing correlationId functionality using express-correlation-id. I am diligently following the guidelines provided on this page: https://www.npmjs.com/package/express-correlation-id. I have successfully imported the ...

What is the process of combining two states in Angular?

Having a state defined as: export interface ChatMessagesState { messages: Message[] | null; chatId: string; } and receiving data in the websocket like: newMessages: Message[] = [ { text: 'Hello', chatId: '100' }, { text ...

Is there a way to access a component based on its route in Angular 7?

I am currently utilizing the NavigationEnd event to identify the current route after it has been changed in the following way: this.router.events.pipe( filter(event => event instanceof NavigationEnd) ).subscribe((event) => { const na ...

Determine the data type based on the object property

Can a versatile function be created to automatically determine the type based on an "external" object property? Consider the following scenario: const resolversMap: { overallRankingPlacement: (issuer: number, args: Record<string, any>, context: Re ...

I'm having trouble with npm install, it's not working as expected

After downloading node.js, I encountered errors when trying to run the CLI command npm install -g @angular/cli: npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! network request to http://registry.npmjs.org/@angular%2fcli failed, reason: getaddrin ...

When you click on the mat-tab label, it will act as a link and directly open the

I am facing an issue where I have 4 mat-tabs and I want to add one more tab. This additional tab will act as a label that, when clicked, opens a provided link. I have tried the following code but it is not working: <mat-tab label="Statistik ...

Having an issue where the Material Angular 6 DatePicker is consistently displaying my selected date as one day earlier

I've encountered a strange issue with the current version of the Material Angular DatePicker. After upgrading from A5 to A6, it started to parse my date one day earlier than expected. You can see an example of this problem here: https://stackblitz.com ...

A guide on representing nested JSON documents in a Java class

JSON consists of a formula along with the values of its parameters. For instance, the sum of a+b is: { formula: "a+b", values: {"a": 3, "b": 5} } Each formula in JSON requires a specific set of values. I aim to develop a Java class that comprises two fie ...

A step-by-step guide on uploading images to Firebase using Ionic 4

I'm having trouble uploading images to Firebase. Can anyone offer assistance? Does anyone know how to upload images to Firebase in Ionic 4.0? The code below used to work in Ionic 2, but now there's a delay of about 30 seconds after clicking the ...

Prepare fixtures for commands in Cypress before executing the hook

One of my main tasks is to load the fixtures file only once and ensure it is accessible across all project files. To achieve this, I created a fixtures.js file with the following content: let fixturesData; export const loadFixturesData = () => { cy ...

Discovering if an input field is read-only or not can be achieved by using Selenium WebDriver along with Java

Currently, I am utilizing selenium webdriver along with Java to create a script. One issue we are encountering is that certain fields become disabled after clicking on a button. We need to determine if these fields are transitioning into readonly mode or ...

What is the process for exporting a plugin from dayjs() in JavaScript?

Currently, I have incorporated the plugin isToday() to enhance the capabilities of dayjs(). Nevertheless, I am uncertain about how to export isToday() in order to utilize it across other files. import isToday from "dayjs/plugin/isToday"; expor ...

Using a reactive form in Angular 12, the selected form group is initialized with an empty array

.html File <div *ngFor="let analysis of analysisFormArray.controls; let i = index" [class.selected]="analysis === selectedAnalysis"> <div [formGroup]="analysis" (click)="onSelect(analysis)"> ...

Inquiring about the application of spread argument in TypeScript

Here is some code I'm working on: import _ from 'lodash'; function test(num1: number, num2: number) { console.log(num1, num2); } test(..._.take(_.shuffle([0, 1, 2]), 2)); I encountered a TS2556 error while using the TS playground and ...

Effortlessly handle submissions in your Spring Ajax controller without the need to refresh the

I have integrated Starbox into my Spring page, and I need to find a way to save the user rating to the database without refreshing the page. How can I set up a Spring controller to handle this value without returning a new view? The goal is for the user&ap ...

Please ensure to close the dropdown menu once the function has been called

I'm encountering an issue with a dropdown menu. When I expand the dropdown menu, everything works as expected. However, is it possible to disable the first search button and the txtSearch input field (referring to the class "glyphicon glyphicon-search ...