"Encountered an issue with Angular 2 when attempting to post data to an API -

After downloading a project from the link provided by ASP.NET on individual accounts in Web API, I managed to run it successfully on VS2015 and IIS Express. However, my goal now is to utilize Angular 2 to call the API.

In order to achieve this, I set up a new project in Visual Studio Code using Angular 2 and TypeScript. Despite my efforts, when attempting to make a POST request to the API method called Register, all the values appear as null.

My Visual Studio Code service (Angular2)

import { Injectable } from 'angular2/core';

import { Account } from '../account/Account';
import { RegisterBindingModel } from '../account/RegisterBindingModel';
import {Http, Response, Headers, RequestOptions} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class AccountService {
    constructor(private _http: Http) {

    }
    
    createAccount(account: Account): Observable<string> {
        console.log('accountService.createAccount');
        let body = JSON.stringify({ account });
        console.log('T1' + body);
      
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

return this._http.post('https://localhost:44305/api/Account/Register', body, options)
                    .map(this.extractData)
                    .catch(this.handleError); 

Issues faced in browser and POST values: https://i.sstatic.net/N7zvb.png

Error messages received from server API: https://i.sstatic.net/7Yx3O.png Error2_In_API_Method https://i.sstatic.net/MjgRz.png

While GET operations work fine, all my POST operations result in NULL values. What could be causing this issue?

Answer №1

In my search for a solution, I came across an unconventional but effective method. I mapped the account class objects to a new object, converted it to a string, and then posted it:

    createAccount(account: Account): Observable<string> {

        var obj = { Email: account.Email, Password: account.Password, ConfirmPassword: account.ConfirmPassword };

            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            let body = JSON.stringify(obj);

            return this._http.post('https://localhost:44305/api/Account/Register',  body, options)
                                .map(this.extractData)
                                .catch(this.handleError);
}

To resolve the first error encountered in the API, I made the following change:

Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

Changed to

HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

This allowed me to access GetOwinContext() from the POST request.

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

How can I loop through a JSON object in Angular 8 using a function?

Within my component.ts file, I have developed a function: getData(id) { const idMod = id const idModN = document.getElementById("idMod").innerHTML = idMod console.log (idModN) } My goal is to click on a button and have the id of each ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Using Razor view form with various submit buttons

In my razor view, I have a BeginForm command surrounded by a loop that generates an HTML table with a submit button in each row. My concern is how do I identify which specific row the submitted form corresponds to when sending it back to the controller? T ...

I am able to upload an image using ImagePicker.openPicker in my React Native app, however, I am encountering difficulties

Currently, I am in the process of developing an application using react native. Within the app, users have a profile image that can be updated by either selecting one from the gallery or capturing a new one with the camera. The library utilized for this ...

Tips on customizing KendoUI-Dialog titlebar using CSS for a single component

I am struggling with styling the KENDO UI dialog in a unique way: Imagine I have a component named WatComponent. Inside this component, When the user clicks the "Forbidden" button, my goal is to make a warning styled dialog appear, with a yellow/orange ...

Steps to validate the execution of the ngCopy function in an Angular 6 unit test

While working on one of my angular components, I have implemented the ngCopy module to enable text copying to clipboard. The code snippet below showcases how I have used this module: import {Component, Input, OnInit} from '@angular/core'; import ...

Printing reports in Angular 9

I have a requirement in my Angular 9 application to generate and print reports. 1. I am looking for suggestions on how to handle printing reports where a user triggers the action by clicking a button, and the report data needs to be fetched from the datab ...

Challenges of implementing dark mode with a checkbox and local storage

I'm experiencing an issue with local storage. When I enable the dark mode, everything functions properly and the local storage 'dark' is set to true. However, upon refreshing the page, the local storage remains true but the toggle switches b ...

A guide on converting database objects into JSON format for API responses in a node environment

Currently utilizing express.js and sequelize.js for API development. When fetching an object from the database with sequelize, I aim to exclude certain object attributes (e.g. hide the User's password hash in the returned JSON) introduce new attribu ...

Upon updating my application from Angular 14 to 16, I encountered an overwhelming number of errors within the npm packages I had incorporated

After upgrading my angular application from v14 to v16, I encountered numerous peer dependencies issues, which led me to use the --force flag for the upgrade process. However, upon compiling, I am now faced with a multitude of errors as depicted in the scr ...

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

Create a d.ts file for Vue components that are written using Typescript

As a newcomer to Vue, I am eager to dive into creating components and publishing packages to NPM. My plan is to develop Vue (typescript) + Vuetify reusable components that can be easily installed from NPM into any of my projects. While I have successfully ...

Utilizing ngFor to iterate over items within an Observable array serving as unique identifiers

Just starting out with Angular and I'm really impressed with its power so far. I'm using the angularfire2 library to fetch two separate lists from firebase (*.ts): this.list1= this.db.list("list1").valueChanges(); this.list2= this.db.list("list2 ...

Image two-way binding in Angular is not performing as anticipated

My Angular component is designed to display a base64 image string received from a websocket in the HTML using an image tag. I am polling the websocket every second and attempting to display the updated image on the page. Here is my code: HTML of the compo ...

Sending properties via react router link in TypeScript

I have successfully defined my routes and made my links functional. I am now trying to figure out how to pass a prop through the link when the component is called by the router. It seems like a challenging task. To understand better, take a look at this c ...

The renderer function is unable to modify the property 'background-color'

Currently, I'm exploring Angular and facing an issue while attempting to change the background color using _renderer.setElementStyle. Unfortunately, it doesn't seem to be applying properly. Can someone offer assistance with this, please? export ...

Is it possible to incorporate advanced transitions and animations using Angular 4?

Looking to incorporate animations using Angular 4 only. I have tried implementing the following advanced animation but struggled with writing parallel div animations in Angular 4. I believe this can be achieved via CSS, but unsure how to do so in Angular 4 ...

Issues with Imported Routes Not Functioning as Expected

I am currently working on implementing routing in my Angular 2 project. All the components are functioning properly, but I encounter an error when I include 'appRoutes' in the imports section of app.module.ts. An unexpected TypeError occurs: C ...

Dealing with Cross-Origin Resource Sharing Problems in Angular 8 REST API

I am currently working with 2 components: The first component, "CurrenciesComponent," is being loaded. @Component({ selector: 'app-currencies', templateUrl: './currencies.component.html', styleUrls: ['./currencies.componen ...