Retrieve a specific data point from a web API using Angular framework

Objective: How can I retrieve the specific value "test" in Angular?

Issue: An error message is being displayed.

Error: SyntaxError: Unexpected token e in JSON at position 1 at JSON.parse ()

Which syntax element am I missing?


ASP.NET

// Retrieve "test" from https://localhost:44353/api/Jobadvertisement/VVValidate/4
[HttpGet("VVValidate/{id:int}")]
public ActionResult<String> VVValidate(int id)
{
    return "test";
}

Angular

const url = environment.url

let apiUrl = url + 'api/Jobadvertisement/VVValidate/' + "4";

var response = this.http.get(apiUrl).subscribe(data => {

  console.log(data);

});

https://i.sstatic.net/au70F.png

https://i.sstatic.net/y5UyR.png

Answer №1

Could you attempt to utilize httpOptions in Angular using the following code snippet?

const apiUrl = environment.apiUrl;
let endpoint = apiUrl + 'api/Jobadvertisement/VVValidate/' + "4"; 
var response = this.http.get(endpoint, { responseType: 'text' }).subscribe(data => { console.log(data); });

Answer №2

To make the necessary change, switch ActionResult to string:

[HttpGet("VVValidate/{id:int}")]
public string VVValidate(int id)
{
    return "test";
}

Answer №3

When working with Angular's HttpClient, it is important to note that it expects JSON data by default. This can cause a JSON deserialization error if you try to return plain text from your API.

To avoid this error, you need to include responseType: 'text' as an option when using the get method:

httpClient.get("url", { responseType: 'text' });

For more information on this topic, refer to Angular's Documentation.

While your API code may currently work fine, there are a couple of improvements that could be made:

  1. You can simplify your code by removing unnecessary wrappers like ActionResult and simply returning a String.
  2. Consider using the C# type string instead of System.String. You can read more about this distinction in this article.

Implementing these changes will result in cleaner code, as shown below:

[HttpGet("VVValidate/{id:int}")]
public string VVValidate(int id)
{
    return "test";
}

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

Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so. groupBy: <Map>(predicate: (item: T) => Map[]) => Map[]; Array.prototype ...

Do I have to utilize npm packages?

As a newcomer to Node.js, I'm diving into the world of node features while working on an Angular 2 project. One thing I've noticed is that every plugin seems to be imported from the node_modules folder. This has me wondering - is it absolutely n ...

What is the procedure for entering the output generated by genMockFromModule when creating a custom mock in Jest?

Looking at my orders directory structure, I have a function in the orders/helpers file that I want to test using a manual Jest mock. orders __mocks__ helpers.ts __tests__ orders.ts helpers.ts orders.ts The orders/helpers.ts file contains ...

Discover the steps to implement user authentication with a combination of username, password, and token in an Angular 4

After developing a form using Angular 4, I encountered the need to send the form data via the post method with Angular 4. Testing with Postman showed that the data is being received correctly. To accomplish this, I must use Basic Auth with a username and p ...

Establishing a connection to the Oracle database

Since today is my first attempt at using Oracle databases in Asp.NET, I am feeling lost and unsure about what steps to take. Here is the code I have added: Dim oOracleConn As OracleConnection = New OracleConnection() oOracleConn.ConnectionString = "Data ...

The Angular Component I've created is displaying a single set of data on each mat-tab screen

I have developed a component with the file name hukamnama-sahib.component.html, which looks like this: <body *ngFor="let dataitem of HukamnamaSahibList"> <h4> <span class="gurmukhi">{{dataitem.line.gurmukhi.unico ...

Issues with navigating the HTML menu are preventing users from properly accessing

Below is the structure of my menu in HTML: <div id=navigation> <ul id=nav> <li> <asp:HyperLink ID=HyperLink1 runat=server NavigateUrl=~/Home.aspx>Home</asp:HyperLink> ...

Craft dynamic SVG components using TypeScript

Looking to generate a correctly formatted SVG element using TypeScript: createSVGElement(tag) { return document.createElementNS("http://www.w3.org/2000/svg", tag); } Encountering an issue with tslint: Error message: 'Forbidden http url in str ...

The Yii2 CORS filter is throwing an error indicating the absence of the 'Access-Control-Allow-Origin' header

After reading through the information provided in this particular question, I have configured my rest controller behavior as follows: public function behaviors() { $behaviors = parent::behaviors(); $auth= $behaviors['authenticator'] = [ ...

Creating dirty or touched input programmatically in Angular2 can be achieved by using the `.markAsT

Looking to integrate a JQuery plugin with Angular2? Essentially, this plugin generates a duplicate of specific HTML content containing inputs. As data is modified, Angular2 automatically re-renders the content along with any errors. However, the challenge ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

What is the best way to add an external .js file to my Angular 2 application?

I'm currently working on a project using Angular 2's TypeScript API along with webpack to develop a web application. However, I've encountered an issue where one of my components needs to utilize functions from an external .js file that is p ...

How can a function be invoked in a class inheriting from System.Web.UI.Page from an MVC3 controller?

Received a cs file from a vendor containing the following structure: public partial class Test : System.Web.UI.Page { public void InsertSignature() { Response.Write("ASDFASDFAF#WRRASDFCAERASDCDSAF"); } } Trying to utilize the Inse ...

Use the mat-slide-toggle to switch up the text style

Is it possible to apply different text styles using Ang-Material-2's mat-slide-toggle? https://i.stack.imgur.com/WM9FC.jpg <mat-slide-toggle [color]="primary" [checked]="true">Slide me</mat-slide-toggle> <h3>Text</h3> ...

Leverage the component's recursive capabilities to build a tree structure from within

Is it feasible to use a component within itself? If so, where can I find more information on this? I am facing the following scenario: I have a list of main items, each main item has a subitem (which looks like the main item), and each subitem can have i ...

Learning how to read SQL query results in C# programming language

Just starting out in c# so please excuse my basic question. I am attempting to let the user perform certain operations based on the result of a sql query. Here is my current approach: SqlConnection oConn = new SqlConnection(); oConn.ConnectionString = "My ...

Verify if a particular string is present within an array

I am in possession of the key StudentMembers[1].active, and now I must verify if this particular key exists within the following array const array= ["StudentMembers.Active", "StudentMembers.InActive"] What is the method to eliminate the index [1] from Stu ...

"Upon receiving a request in Net Core 6 + Angular, null properties are detected in the

Greetings! I am currently working on a project using .NET Core 6 with Angular 12. Within my project, I have a login controller along with its corresponding request model. Interestingly, when I execute the request through Swagger or Postman, everything wo ...

The Subscription request did not trigger as expected

I encountered an issue where I needed to call two services in the OnInit step, but the second request was not being sent. As a workaround, I had to call them sequentially, which I believe is not the most efficient way to write the code. (Both services on t ...

Error message 512 occurred in test procedure at line 21 due to a subquery returning multiple values instead of a single value

ALTER PROCEDURE [dbo].[test] @tour int, @tourname varchar(50) OUTPUT, @tourdepartures varchar(50) OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statement ...