Spring Boot fails to recognize path variable data sent from Angular

When working with Angular 7, I encountered a situation where I needed to pass a value from the service class of Angular. Here is how I achieved it:

executeHelloWorldBeanServiceWithPathVariable(name){
    console.log("name coming from here"+name);
    return this.httpClient.get<HelloWorldBean>('http://localhost:8080/hello-world/path-variable/${name}');
     console.log("hello world bean service executed");
   }

After testing, I confirmed that the name was successfully printed in the console as expected:

console.log("name coming from here"+name);

There were no issues with printing the name in the console.

https://i.stack.imgur.com/bHr3A.png

In my Spring Boot application, I defined the endpoint as follows:

@GetMapping(path="/hello-world/path-variable/{name}")  
    public HelloWorldBean helloWorldBeanPathVariable(@PathVariable("name") String name) {
        System.out.print("name is"+name);
        return new HelloWorldBean(String.format("Hello world %s", name));
    }

However, when trying to print the passed parameter in the Spring Boot application using

System.out.print("name is"+name);
, I faced some difficulties as the name was not being displayed in the console as expected.

This issue led me to explore further and check how the name would appear through EL expressions instead:

https://i.stack.imgur.com/QcKcE.png

Ultimately, despite the debugging challenges, the UI output showed the correct result:

https://i.stack.imgur.com/s8mGU.png

Answer №1

It appears that you may not be utilizing the correct syntax for template literals in your

executeHelloWorldBeanServiceWithPathVariable
method. I assume you are attempting to do so based on the presence of the ${} expression.

This could be causing the request not to parse correctly. Ensure that you use backticks (`) instead of single or double quotes.

executeHelloWorldBeanServiceWithPathVariable(name){
  return this.httpClient.get<HelloWorldBean>(`http://localhost:8080/hello-world/path-variable/${name}`);
}

Additionally, to effectively retrieve the observables from the API request, you will need to subscribe() to it within the component that requires it.

For example:

constructor(
  private yourService: YourService,
) { }

ngOnInit() {
  this.yourService.executeHelloWorldBeanServiceWithPathVariable('someName').subscribe(res => {
    console.log(res);
    // add further actions here
  })
}

Answer №2

Remember to always use backticks ` instead of single quotes ' or double quotes " when concatenating strings in TypeScript, especially when evaluating a value such as `${myname}`

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

Mastering Inter-Composable Communication in Vue 3: A Guide

Composables in Vue documentation demonstrate how small composition functions can be used for organizing code by composing the app. Discover More About Extracting Composables for Code Organization "Extracted composables act as component-scoped servi ...

The data type 'boolean' cannot be assigned to the type 'CaseReducer<ReportedCasesState, { payload: any; type: string; }>'

I recently developed a deletion reducer using reduxjs/toolkit: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { AppThunk } from "../store"; import { ReportedCase, deleteReportCase } from "../../api/reportedCasesApi"; import history ...

How to Access Static Method from Non-Static Method in TypeScript

Within my hierarchy, there is some static content present in all levels (for example, the _image). It would be ideal to access the corresponding _image without repeating code: Here's what I envision: class Actor { static _image; // Needs to be s ...

Error suddenly appeared when trying to serve a previously functional project locally: Firebase function module not found

After not making any changes to my firebase-related files, I suddenly started encountering the following issue that I just can't seem to figure out: We were unable to load your functions code. (see above) - It appears your code is written in Types ...

Angular D3 - The method 'getBoundingClientRect' is not present in the 'Window' type

Check out this StackBlitz demo I created: https://stackblitz.com/edit/ng-tootltip-ocdngb?file=src/app/bar-chart.ts In my Angular app, I have integrated a D3 chart. The bars on the chart display tooltips when hovered over. However, on smaller screens, th ...

Creating a variable that is not defined and then converting it into

I have an issue with a function that returns an Observable. The problem is that when the function is called, the parameter works fine, but its value becomes undefined within the Observable. This is the function in question: import {Observable} from &apos ...

Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum. Imagine you have the following: enum Gender { Male = 1, Female = 2 } If you write: for (let gender in Gender) { console.log(gender) } You will notice that it iter ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

An error was detected in the card-module.d.ts file located in the node_modules folder within the @angular/material/card/typings directory

Currently, I am working on an angular project using Visual Studio Code as my text editor. When attempting to open the project with 'npm start', an error occurred. The specific error message is: ERROR in node_modules/@angular/material/card/typing ...

A mistake has been identified: The object could potentially be 'null'. TS2531 for window.document

This is my first time integrating TypeScript into my project. When attempting to access something using window.document.getElementById(), I keep encountering the error: Type error: Object is possibly 'null'. TS2531 I've looked online for ...

Determining the data type of an object key in Typescript

Is there a way to limit the indexed access type to only return the type of the key specified? interface User { id: string, name: string, age: number, token: string | null, } interface Updates<Schema> { set: Partial<Record< ...

Determine the return type of a function based on a key parameter in an interface

Here is an example of a specific interface: interface Elements { divContainer: HTMLDivElement; inputUpload: HTMLInputElement; } My goal is to create a function that can retrieve elements based on their names: getElement(name: keyof Elements): Elemen ...

Issue with VS2017RC: TypeScript fails to produce JavaScript files

After updating to VS 2017, I noticed that modifications made to a typescript file no longer result in the generation of any javascript code, despite receiving a message indicating "outputs generated successfully" on the lower bar. I tested this issue on t ...

Trigger a table refresh to display updated information

When I select the select option to make an API call for a new datasource, my table appears before fetching data and it remains empty. Additionally, if I choose another select option, it displays the previous data from the previous selection. I have attemp ...

Tips for creating TypeScript Google Cloud Functions using webpack

I'm currently facing a challenge while coding a Google Cloud Function using TypeScript. The concept involves having handler functions defined for various Cloud Functions in separate files within the source repository, along with some code that is shar ...

Use PipeTransform to apply multiple filters simultaneously

Is it possible to apply multiple filters with PipeTransform? I attempted the following: posts; postss; transform(items: any[]): any[] { if (items && items.length) this.posts = items.filter(it => it.library = it.library ...

How to access the component instance in Angular through router events

I am currently working on incorporating a title service into my Angular 10 application. My goal is to subscribe to router events, access the activated route's component, check if it has a title() getter, and then use that information to set the page&a ...

Customizing the appearance of the Material UI MuiClockPicker with unique style

I am wondering how I can override the styles for MuiClockPicker? I discovered that using createTheme to override the styles actually works for me, but I encountered an error from TypeScript: TS2322: Type '{ MuiOutlinedInput: { styleOverrides: { roo ...

Using regular expressions, replace all instances of " " with ' ' based on certain conditions

I am looking to replace quotes "" with single quotes '' within a string. string = `bike "car" bus "'airplane'" "bike" "'train'"` If a word is inside double quotes, it shoul ...

Exploring JSON data in real-time

My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs. Although the code works flawlessly when I manually s ...