Struggling with hashtags and ampersands in Angular when making an HTTP request

Dealing with Special Characters # and & in Angular's http.get() Request URL

Take a look at my code first.

Angular Service

let versionsearch = "&";
let strweeksearch = "%23";

this.http.get(this.apiUrl + 'GetVersionInfo?vehicleVersion=' + versionsearch + '&structureWeek=' + strweeksearch,
            { withCredentials: true })
            .map(response => <CoCApiResponse[]>response.json())
            .catch(error => {
                return Observable.throw(error);
            });

Web API

  [HttpGet]
  public CoCApiResponse GetVersionInfo([FromQuery]string vehicleVersion, [FromQuery]string structureWeek)
        {
            //code
        }

Explanation and Questions:

I have a GET method in the Web API with two string parameters. I am calling that REST service from the Angular http service via a query string which passes those parameters. However, if I pass values like "#" or "&" in the query string, I encounter the following problems.

Using "#":

The API URL breaks when passing "#" in the query string.

But I found a solution from this discussion: Passing a pound sign as a value in the query string of a URL using Angular

So I replaced "#" with "%23" in the Angular service like

strweeksearch.replace(/#/g, '%23');
.


Using "&":

The API URL treats it as three parameters, like

apiurl?versionsearch=&&strweeksearch=123455

As a result, the Web API method parameter "vehicleVersion" always receives NULL.


How can I handle this situation without having to replace every special character with reserved characters? I want all special characters to be accepted in the http.get(). How do I address this in Angular or the Web API?

Answer №1

When you include version search in your get() and concatenate the string with '&', it appears as if you are passing 3 parameters.

this.http.get(this.apiUrl + 'GetVersionInfo?vehicleVersion=' + versionsearch + 'structureWeek=' + strweeksearch,
            { withCredentials: true })
            .map(responce => <CoCApiResponse[]>responce.json())
            .catch(error => {
                return Observable.throw(error);
            });

Perhaps consider removing one parameter!

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

Node.js is being utilized to send an abundance of requests to the server

Here is my setup: var tempServer=require("./myHttp"); tempServer.startServer(8008,{'/fun1':fun1 , '/fun2': fun2 , '/fun3':fun3 , '/fun4':fun4},"www"); This code creates a server on localhost:8008. If I enter th ...

Angular error: Attempting to reduce an empty array without an initial value

I am encountering an issue with my array being filtered and reduced. getPageComponents(title: string) { this.pageComponents = []; const pageBlock = this.pageComponents.filter((val) => { if (val.page_title === title) { retur ...

Angular4 and jQuery working together for effective navigation and pagination

Trying to implement pagination in angular 4 and jQuery, but encountering an issue where clicking on the next button causes it to skip through multiple pages at once (2, then 3, then 5)... Component code: addClass(x) { $(".page-item").click(function () ...

Tips for displaying a modal popup in Angular with content from a separate page

I want to display a modal popup on a different page that has its body content in the app.component.html file. App.Component.html: <ng-template #template> <div class="modal-header"> <h4 class="modal-title pull-left">Modal ...

Store the fetched data as JSON in the local storage

Struggling to find a solution after reading several articles, I am working on fetching a large JSON from an API and I want to cache the response in the localStorage. The goal is for the script to check for an object with the requested ID in the cached JSON ...

Merge two separate mongodb records

Just getting started with javascript / express / mongodb. For my initial project, I am working on a simple task manager where todos are categorized by priority - "high," "mid," or "low." However, I am facing an issue when trying to display different entri ...

Exploring ways to display dynamic content within AngularJs Tabs

I need help figuring out how to display unique data dynamically for each tab within a table with tabs. Can anyone assist me with this? https://i.stack.imgur.com/63H3L.png Below is the code snippet for the tabs: <md-tab ng-repe ...

Troubleshooting an issue with an AJAX request

Having trouble getting the HTML back from an AJAX call - works in FF but returns "null" in IE when using alert(result.html()); Here's the code, any suggestions? Thanks! The errors variable is also null in IE. It doesn't matter what element I u ...

The data type 'string | null | undefined' cannot be assigned to the data type 'string | undefined'

In my Angular application using Typescript, I have the following setup: userId?: number; token?: string; constructor(private route: ActivatedRoute) { this.route.queryParamMap.subscribe( (value: ParamMap) => { this.userId = val ...

Ways to eliminate a single child from a jQuery object without altering the HTML structure

My code snippet looks like this: $.fn.extend({ del: function() { } }) var ds = $(".d"); ds.del(ds[0]) console.log(ds.length) I am trying to use jquery.del to remove a child from some jquery elements without altering the HTML. Any suggest ...

Error: The function "text.toLowerCase()" is not defined

Whenever I execute the following code, I keep encountering this error message: Uncaught TypeError: text.toLowerCase is not a function const getVisibleExpenses = (expenses, { text, sortBy, startDate, endDate }) => { return expenses.fi ...

Receive a notification for failed login attempts using Spring Boot and JavaScript

Seeking assistance with determining the success of a login using a SpringBoot Controller. Encountering an issue where unsuccessful logins result in a page displaying HTML -> false, indicating that JavaScript may not be running properly (e.g., failure: f ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

How can I successfully implement the Add To Calendar Button Package?

Recently, I decided to incorporate this particular component into my application. Although it seemed simple enough at first, I'm now faced with a puzzling TypeError originating from within the package. The react component I am constructing is as foll ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Illuminating individual table cells as a user drags their mouse across a row

My goal is to create a feature that allows users to highlight cells in a table by dragging the mouse over them, similar to what is discussed in the question and answer provided here. However, I would like to limit this drag/highlight effect to only span w ...

Addon for Firefox: Image Upload

I am looking for a way to streamline the process of uploading an image to a website through a Firefox Addon. While I know it is possible to use createElement('canvas'), convert Image data to base64, and XHR POST the data, I would prefer to lever ...

Show just three items simultaneously

I am currently working on a quote generator and I want to add a feature that allows me to display a specific number of quotes at a time. I attempted to use map for this purpose, but encountered an error stating it's not a function. Currently, the gene ...

TypeScript compilation will still be successful even in the absence of a referenced file specified using require

Having both Project 1 and Project 2 in my workspace, I encountered an unusual issue after copying a file, specifically validators/index.ts, from Project 1 to Project 2. Surprisingly, TypeScript compilation went through successfully without showing any erro ...

What are some steps I can take to diagnose why my Express server is not receiving POST requests from my HTML form?

Struggling with an unexpected issue on my website where the form submission is not triggering the POST request to my Express server. I've set up a MongoDB database and created a HTML form to store user data, but something seems to be amiss. HTML: & ...