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"));