What is the process for performing interpolation in Angular version 8?

In my Angular project, I have 2 components working together. Component A sends an id using the following code snippet:

<a [routerLink]="['/numbersbyareacode', element.id]">
   {{element.title}} 
</a> 

Upon navigating to Component B, it retrieves the id and stores it in a local variable called `id` as shown in the TypeScript class of Component B. When the id is printed to the console, it displays the correct value.

Here is Component B:

id: any;

constructor(private route: ActivatedRoute, private httpClient: HttpClient) {
}

ngOnInit() {
  this.id = this.route.snapshot.paramMap.get('id');
  console.log(this.id);
  this.getAllNumbersByAreacode();
  this.dataSource.paginator = this.paginator;
}

getAllNumbersByAreacode() {
    // tslint:disable-next-line: max-line-length
    this.httpClient.get('http://localhost:8080/p/api/v1/phonenumbers/
    getN/${id}').subscribe((res: any[]) => {         //this interpolation doesn't work
      console.log(res);
    });
}

Despite my efforts to include the id in the path, I seem to be facing an error with the URL format, which appears like this in the console:

"http://localhost:8080/p/api/v1/phonenumbers/getN/$%7Bid%7D"...

I am seeking guidance on what might be causing this issue. Any insights would be greatly appreciated.

Answer №1

Angular isn't the focus here, it's all about javascript. When using template literals, remember to enclose your strings in backticks instead of single quotes. Learn more about template literals here.

So make sure to use backticks (`) like this:

this.httpClient.get(`http://localhost:8080/p/api/v1/phonenumbers/getN/${id}`)
    .subscribe((res: any[]) => {
      console.log(res);
    });

Answer №2

Perhaps a simple tweak from ('') to (``) will do the trick.

The single quote (') functions as a regular string character, while the backtick (`) is like a "smart" string known as template literals.

this.httpClient.get(`http://localhost:8080/p/api/v1/phonenumbers/getN/${id}`)

If you opt for ('), remember to concatenate using +.

this.httpClient.get('http://localhost:8080/p/api/v1/phonenumbers/getN/' + id)

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

What could be causing routerLink to malfunction despite correct configuration?

Is routerLink properly placed in the view? <p><a routerLink="/registration" class="nav-link">Register</a></p> Checking my app.module import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular ...

What is the best way to set up role redirection following a successful login within my MEAN stack application?

I have successfully developed a MEAN stack application with a functioning backend and frontend. However, I am looking to enhance it further by implementing role-based redirection after login. There are 5 roles in the system: admin, teacher, nurse, sportsma ...

Navigating to the detail page following a POST request in RTK query: A step-by-step guide

In my React RTK-query form, I am facing an issue where after a POST request is made, the form should navigate to the next step. However, in order to do that, I need to obtain the id of the newly created record. The backend auto-increments the id and does n ...

What causes the discrepancies in versions of dependencies listed in the package-lock.json file?

Currently, I am developing an application using angular 10. I have noticed that the version of a dependency in my package-lock.json file is different from what I specified in my package.json after running the command: npm install. For example: In my pack ...

Create a tuple type by mapping an object with generics

I have a specified object: config: { someKey: someString } My goal is to generate a tuple type based on that configuration. Here is an example: function createRouter< T extends Record<string, string> >(config: T) { type Router = { // ...

How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below: export enum XMPPElementName { state = "state", presence = "presence", iq = "iq", unreadCount = "uc", otherUserUnreadCount = "ouc", sequenc ...

Issue encountered while deploying Next.js application on vercel using the replaceAll function

Encountering an error during deployment of a next.js app to Vercel, although local builds are functioning normally. The issue seems to be related to the [replaceAll][1] function The error message received is as follows: Error occurred prerendering page &q ...

Using TypeScript's reference function within an HTML document

It feels like ages since my early days of web development. Back when I first started coding, we would reference a script using a <script> tag: <html> <head> <script src="lealet.js"></script> <!-- I know the path isn´t c ...

Missing 'id' property in ngFor loop for object type

I'm currently learning Angular and I've been following a code tutorial. However, despite matching the instructor's code, it doesn't seem to be working for me. When I try to compile the following code, I receive an error message stating ...

Generate a fresh JSON object following a click event triggered by an HTTP PUT request

I have the following structure in JSON format: "disputes": [ { id: "", negotiation_type: "", history:{ user_flag: "", created_at: "", updated_at: "", created_by: null, updated_by: null, ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

Looking to display the ng-option in two lines within Angular 6?

How can I display data in a select dropdown with two lines for each option? I am currently using ng-select. <ng-select [(ngModel)]="selectedData" placeholder="Select Data"> <div *ngFor="let data of Data"> <ng-option [value]="da ...

Accessing the .env file to configure a NestJS application using TypeORM and a custom provider

I am still learning my way around nestJS and I am currently trying to configure .env for an existing application but encountering some issues. Within my custom provider for the appModule, it looks like this: @Module({ providers: [ AbcService, ...

Creating an HTTP gateway with Observables

When dealing with multiple requests, I need to pause them until the authentication of the http request has been confirmed. Essentially, I require an http gate where some requests can pass without authentication, while others need to wait for the token to b ...

"Is there a way to extract a value from a JSON object using

I have an object with the following key-value pairs: { 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812', 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1&a ...

Limit the usage of typescript to ensure that references to properties of 'any' object are verified

I'm facing a situation where I have a JS object called myObject, and it is of type any. Unfortunately, I cannot change the type as it's coming from a library. The issue I encounter is that when trying to access a property from myObject, TypeScri ...

Keep displaying the default angular loading screen until the angular2 router is fully resolved

Angular2 CLI has a default loading screen that displays until the app gets bootstrapped with <app-root>Loading...</app-root>. Once this is done, the Angular2 route resolver makes an API call to verify whether the user is authenticated before n ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

React error: The DatePickerProps generic type must have one type argument specified

Date Selection Component: import React from "react" import AdapterDateFns from '@mui/lab/AdapterDateFns'; import { LocalizationProvider } from '@mui/lab'; import { DatePicker, DatePickerProps } from '@mui/lab'; cons ...

What are the steps to organize an array of objects by a specific key?

Experimented with the following approach: if (field == 'age') { if (this.sortedAge) { this.fltUsers.sort(function (a, b) { if (b.totalHours > a.totalHours) { return 1; } }); this ...