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

The reason why Type zzz cannot be assigned to type (zzz & NgIterable<xxx>) | undefined | null

Why am I receiving the message in Angular 9 that says: Type Items is not assignable to type (Items & NgIterable) | undefined | null? Despite the fact that the model is correct and there are no errors in the data, I still encounter this TypeScript warn ...

The value of a checkbox in Angular 10 is coming out as undefined

Within my component, I set up the formGroup as shown below: constructor(private apiService: ApiService) { this.form = new FormGroup({ product: new FormControl(), shops: new FormGroup({}) }); } When selecting a vendor from a drop-do ...

Tips for finding elements with Selenium and Java

<input class="chkbx-selection ng-pristine ng-untouched ng-valid" type="checkbox" value="test" id="isAgreeChkBox" ng-model="$root.isAgreement"> Could someone assist me in identifying the xpath/css selector for the above code? I am looking to locate t ...

React.js - Issue with table not being redrawn after data filtering

I am encountering an issue with my table in Next.js where the text input is not triggering a redraw. The expected behavior is to update the table with a single search result, but currently only the top row reflects the search result. Below is my useEffect ...

Creating a variety of themes with unique color palettes for Angular Material along with custom-designed components

One of the goals for my app is to have multiple themes, including Angular Material themes, with the ability to define custom colors for specific components and elements that are not part of Angular Material. It's important that when I change a theme, ...

Modify the property of the ChildComponent by utilizing the ViewChild method

I recently started exploring Angular and I've been experimenting with ViewChild and ViewChildren. In one scenario, I have a property called today = new Date() in my Component2. I'm accessing this property in Component1 using ViewChild and continu ...

Utilizing the JavaScript Array.find() method to ensure accurate arithmetic calculations within an array of objects

I have a simple commission calculation method that I need help with. I am trying to use the Array.find method to return the calculated result from the percents array. The issue arises when I input a price of 30, as it calculates based on the previous objec ...

Opening the Gmail app from a link using JavaScript

What is the best way to open the Gmail app from a hyperlink? This link opens WhatsApp <a href="https://wa.me/">whatsapp</a> <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a1f190f ...

Learn the process of synchronously loading forms and data in Angular

Looking to synchronize the loading of data and form... Let's start by reviewing the code: ngOnInit() { if (this.data.fromCalendar) { this.singleTraining(); } }, 200); this.formControl(); } formControl() { this.gib ...

Developing and employing Services in Angular 2

Having some trouble with Angular2 as I explore it for the first time, specifically in creating and using a service. I've set up a data service like this: import {Injectable} from 'angular2/core'; import {recentActivity} from './app/com ...

Having trouble with installing Bootstrap in Angular 5

My journey with Bootstrap began by executing the command below: npm install --save bootstrap The installation was a success, and I proceeded to incorporate the CSS as follows: "styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css", ...

Emphasize cells and headers when a cell's value deviates from its initial value

I implemented cell editing in my primeng table. Here is the code: <div class="card"> <p-table [value]="products" dataKey="id" [tableStyle]="{ 'min-width': '50rem' }"> <n ...

What is the best way to employ document.addEventListener in TypeScript?

I am currently learning Ionic v2 and I am using document.addEventListener, but I am encountering errors as shown below: > [11:10:21] ionic-app-scripts 0.0.47 [11:10:21] build dev started ... [11:10:21] clean started ... [11:10:21] clean finished in ...

Problem with sequential promises

import { Observable } from 'rxjs/internal/Observable'; export function createHttpObservable(url: string) { console.log('Url is', url); return Observable.create(observer => { fetch(url) .then(response => { ...

Encountering an "ORA-06550 SQLException" while invoking a PL/SQL function from Java

Utilizing Java to extract data from a database and exhibit it is my goal, hence the creation of this PL/SQL function that generates a cursor: create or replace function std_getInfoFunc return types.cursortype as my_cursor types.cursorType; begin ...

Checking for array equality in Java

As a beginner, I am in need of assistance with creating a method that checks whether two arrays are equal in both values and order. The function should return true if the arrays are identical, otherwise it should return false. However, when I tested my c ...

Can you please suggest a way to integrate nguyenhoanglam:ImagePicker:1.6.3 into an Android Java application?

I had been utilizing the nguyenhoanglam:ImagePicker:1.3.2 library in my Android Java project for quite some time. However, due to restrictions imposed by the Play Store on API versions, I was required to update the SdkVersion as follows: minSdkVersion 21 ...

Is there a way to use dot notation in TypeScript for a string data type?

I'm currently in the process of developing a function API with a specific format: createRoute('customers.view', { customerId: 1 }); // returns `/customers/1` However, I am facing challenges when it comes to typing the first argument. This ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

What is the essential Angular 2 script that must be included for a simple Angular 2 application to function properly?

I'm currently working through the latest Tuts+ tutorial on Angular 2 In the tutorial, the author references adding this script: <script src="node_modules/angular2/bundles/angular2.sfx.dev.js"></script> However, in the most recent beta re ...