"Struggling to Get Angular2 HttpClient to Properly Map to Interface

Currently, I am integrating Angular with an ASP.NET WebApi. My goal is to transmit an object from the API to Angular and associate it with an interface that I have defined in Typescript.

Let me show you my TypeScript interface:

export interface IUser {
    userId: number;
    username: string;
}

This is how the object looks on the backend:

public class UserDto
{
    public int UserId { get; set; }
    public string Username { get; set; }
}

Below is the call made from my User service:

get(userId: number): Observable<IUser> {
    return this._http.get<IUser>(this._getUrl);
}

At this point, I'm attempting to utilize the received object:

ngOnInit(): void {
    this._userService.get(1).subscribe(data => { 
        this.user = { 
          userId: data.userId, username: data.username 
        };
      });
  }

Here's the function within the controller called by the API:

    [HttpGet]
    [Route("Get")]
    public HttpResponseMessage Get()
    {
        return Request.CreateResponse(HttpStatusCode.OK, _userLogic.Get(1));
    }

In case you require it, here is the _userLogic.Get() function (using test data):

    public UserDto Get(int userId)
    {
        UserDto d = new UserDto()
        {
            UserId = 1,
            Username = "test"
        };

        return d;
    }

The problem I am facing is that the returned object does not seem to be mapping correctly to my IUser Typescript interface. When debugging, I noticed the following issue:

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

It appears that the mapping component is being ignored or overlooked, as the object is simply returned as-is from the WebApi.

Consequently, data.userId ends up being undefined. Although using data.UserId will work, it lacks the advantages of mapping to the Typescript object (specifically, IntelliSense).

Any suggestions or insights would be greatly appreciated!

EDIT Despite taking Mike Tung's advice into account, the issue persists.

https://i.sstatic.net/1z6zb.png

EDIT I managed to resolve this matter. To properly serialize my objects from the WebApi, I needed to include the following lines in the WebApiConfig. Thank you for your assistance.

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
                new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new 
          System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

Answer №1

It's best to manually handle the mapping process.

fetchUser(id: number): Observable<IUser> {
    return this._http.get(this._getUrl).map(res => //convert response to object);
}

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 T and null for useRef in React is now supported through method overloading

The React type definition for useRef includes function overloading for both T|null and T: function useRef<T>(initialValue: T): MutableRefObject<T>; // convenience overload for refs given as a ref prop as they typically start with a null ...

"Enhancing Angular's `mat-table` with bi-directional data binding

I'm running into an issue with the binding of mat-checkbox within a mat-table. The table's dataSource is a simple array of objects, each containing a boolean property for selection. However, I can't seem to get the two-way binding working pr ...

Issues arising with code splitting using React HashRouter in a project utilizing Typescript, React 17, and Webpack 5

Encountered build issues while setting up a new project with additional dependencies. package.json: { "name": "my-files", "version": "1.0.0", "description": "App", "main": " ...

Reasons Why Optional Chaining is Not Utilized in Transpiling a Node.js + TypeScript Application with Babel

Currently, I am delving into Babel in order to gain a deeper understanding of its functionality. To facilitate this process, I have developed a basic API using Node.js and TypeScript. Upon transpiling the code and initiating the server, everything operates ...

The parameter type '(req: Request, res: Response, next: NextFunction) => void' does not match the type of 'Application<Record<string, any>>'

I'm currently working on an Express project that utilizes TypeScript. I have set up controllers, routers, and implemented a method that encapsulates my controller logic within an error handler. While working in my router.ts file, I encountered an err ...

I am having trouble getting the data to display properly from an API using Angular 16

I'm facing an issue with displaying data fetched from an API. I have reviewed the code multiple times but couldn't find any errors. My console is free of errors and the pagination is visible in the browser, but the expected data is missing. I am ...

Error: The typography-config in Angular 4.x is causing an invalid CSS issue in Sass

I'm looking to incorporate my custom fonts into my Angular 4.x project from the assets folder. I am also utilizing Angular Material for which I am defining custom typography in my styles.sass Below is the code snippet: @import '~@angular/materi ...

Adding up the numbers with JavaScript

Hello everyone, I've been working on some transformations and now I'm left with an array of objects: Can anyone help me come up with a flexible function that will generate a new object where each data[i] is the sum of values from the previous ob ...

Typescript loading icon directive

Seeking to create an AngularJS directive in TypeScript that wraps each $http get request with a boolean parameter "isShow" to monitor the request status and dynamically show/hide the HTML element depending on it (without utilizing $scope or $watch). Any ...

Expanding material UI theme choices through module augmentation is currently ineffective with TypeText

For those experiencing the issue, a codesandbox has been provided for convenience. Click here to access the codesandbox. Curiously, the TypeText feature is not functioning properly while the SimplePaletteColorOptions is working as expected. Despite being ...

How can we prevent new chips (primeng) from being added, but still allow them to be deleted in Angular 2?

Hey there! I'm currently exploring how to make the chips input non-editable. I am fetching data objects from one component and using the keys of those objects as labels for the chips. Check out my HTML code below: <div class="inputDiv" *ngFor="le ...

Utilizing Node.js Functions for Sharing Database Queries

When it comes to sharing DB query code among multiple Node.js Express controller methods, finding the best practice can be challenging. Many samples available online don't delve deeply into this specific aspect. For instance, let's consider a ge ...

Navigating with Angular router in a Bootstrap navigation bar

My link is not displaying as a tab (I'm using Bootstrap 4 and Angular 5). Instead, it shows up as just a plain link. This seems like it should be a simple issue, but this is my first time working with bootstrap... Thank you! <div> <nav cla ...

Palantir Forge: Enhancing Column Values with Typescript Functions

I am seeking assistance with a TypeScript function related to ontology objects. I want to develop a TypeScript program that accepts a dataframe as input. The objective is to nullify the values in other columns when a value from a row in a particular column ...

Error message: "An issue has been encountered within Angular 4 where it is

Thank you for any assistance, I realize this may be a beginner question... but I seem to be missing something and my TypeScript code is error-free. My goal is simple: I want to track which Main Menu Item is currently selected. To achieve this, I have bou ...

Combining storybook and stencil: A comprehensive guide

I'm currently working on integrating storybook with stencil, but the stencil project was initially set up with the app starter using npm init stencil. Here's how it looks I've been researching how to use stencil with storybook, but most res ...

Is it Better to Perform Manual Change Detection in AngularJS or Angular 2?

My issue involves working with a sizable data list where each element has a filter applied. In order to optimize performance due to potentially adding numerous attributes to each entry, I seek to update the list only when there is a change in the data (eve ...

Having trouble obtaining the ref.current.offsetWidth?

I have been working on creating a contextMenu. My goal is to retrieve the offsetWidth and offsetHeight from ref.current, but when I console.log it, it shows as undefined. const ContextMenu: React.FC<ContextMenuProps> = props => { const thisCom ...

What is the most effective method for handling numerous HTTP requests upon the initialization of an application?

Within my Angular application, I am facing the challenge of executing multiple (6) HTTP requests from different sources during initialization. Currently, I am using app_initializer and promise.all() to achieve this. However, the issue lies in the fact that ...

There is no 'next' property available

export function handleFiles(){ let files = retrieveFiles(); files.next(); } export function* retrieveFiles(){ for(var i=0;i<10;i++){ yield i; } } while experimenting with generators in T ...