0

i have two solutions 1. ASP.NET web application(.Net framework)(Web Api) 2. ASP.NET Core application(.Net Core)

in Visula Studio 17.

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, RequestMethod } from 
'@angular/http';
import 'rxjs/Rx';

import { Employee } from '../models/Employee'

@Injectable()
export class EmployeeManagementService {
constructor(private http: Http) {
 }    
}

addEmployeeDetails(employeeDetails: Employee) {

    var obj = {Firstname: employeeDetails.FirstName, LastName: employeeDetails.LastName, PhoneNumber: employeeDetails.PhoneNumber};

    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
    let options = new RequestOptions({ method: RequestMethod.Post, headers: headers });

    let emp = JSON.stringify(obj);

    return this.http.post('http://localhost:xyz/api/employee-management/create-employee', emp, options)
        .map((res: Response) => res.json())
        .toPromise();

APIController

public class EmployeeManagementApiController : ApiController
 {
    //Create Employee
    [HttpPost]
    [Route("api/employee-management/create-employee")]
    public IHttpActionResult CreateEmployee([FromBody]Employee emp)
    {
        EmployeeService service = new EmployeeService();
        var serv = service.CreateEmployee(emp);

        if (serv.status == 1)
        {
            return Ok(emp);
        }
        else
            return new ResponseMessageResult(Request.CreateResponse(HttpStatusCode.PreconditionFailed, serv.message));
    }
}

Employee.ts file

export class Employee {
FirstName: string;
LastName: string;
PhoneNumber: string;
}

Api Employee class file

public class Employee
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string PhoneNumber { get; set; }
}

My html file

<div class="row">
    <app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>
    <div class="col-md-6">
        <br /><br />
        <h3 style="padding-left:20px;color: #6699CC;font-family:'Bookman Old Style'"><u>Employee Management</u></h3>

        <div class="col-md-12">
            <h4>
                <em style="color: red">*</em> First Name:
            </h4>
            <input type="text" class="form-control input" [(ngModel)]="emp.FirstName" placeholder="Enter Name" /><br />
        </div>

        <div class="col-md-12">
            <h4>
                <em style="color: red">*</em>Last Name
            </h4>
            <input type="text" class="form-control input" [(ngModel)]="emp.LastName" placeholder="Enter Name" /><br />
        </div>

        <div class="col-md-12">
            <h4>
                <em style="color: red">*</em>Phone Number
            </h4>
            <input type="text" class="form-control input" [(ngModel)]="emp.PhoneNumber" placeholder="Enter Name" />
             <br /><br />
        </div>

        <div class="col-md-12" align="left">

            <button style="color:white" class="btn btn-primary" (click)="addEmployee(emp)">Submit</button>
            <button class="btn btn-primary" (click)="clearEmployee()">Clear</button>
        </div>

    </div>
</div>

Add component

import { Employee } from '../../models/Employee';
import { EmployeeManagementService } from '../../services/employee-
managment.service';
import 'rxjs/Rx';

@Component({
selector: 'emp-add',
templateUrl: './employee-add.component.html'
})
export class AddEmployeeComponent {
 emp;
 constructor(private employeeService: EmployeeManagementService) {
    this.emp = new Employee();
 }


addEmployee(emp) {
    this.employeeService.addEmployeeDetails(emp);
    this.clearEmployee(emp);
}

My ts file is in on solution and my api is in another solution. here am getting calls to my API but emp values are all null. Am i missing anything . Please help me out.

same code i have tried with normal controller in same Solution , if i send single parameter values is passed to API controller.

Thanks in advance

3
  • Where do you use addEmployeeDetails? Commented May 16, 2017 at 9:28
  • import { Employee } from '../../models/Employee'; import { EmployeeManagementService } from '../../services/employee-managment.service'; import 'rxjs/Rx'; @Component({ selector: 'emp-add', templateUrl: './employee-add.component.html' }) export class AddEmployeeComponent { emp; constructor(private employeeService: EmployeeManagementService) { this.emp = new Employee(); } addEmployee(emp) { this.employeeService.addEmployeeDetails(emp); this.clearEmployee(emp); } Commented May 16, 2017 at 9:29
  • <button style="color:white" class="btn btn-primary" (click)="addEmployee(emp)">Submit</button> Commented May 16, 2017 at 9:29

3 Answers 3

1

Observables are by default "cold" you need to subscribe to them, in order to fire them

this.employeeService.addEmployeeDetails(emp).subscribe((response)=>{
    console.log(response);
});

In your case, if you use .toPromise() you should use then

this.employeeService.addEmployeeDetails(emp).then((response)=>{
    console.log(response);
});

Check your network tab to see if you are actually making the request: enter image description here

In your network tab when you click your button you should see a post request.

Then check your request:enter image description here

Link of the plunker I used: http://plnkr.co/edit/HR8l5kYlar4XxmgxLa9Z?p=preview

Sign up to request clarification or add additional context in comments.

30 Comments

Sorry i think you havent understood my question here am sending my obj as emp "return this.http.post('localhost:xyz/api/employee-management/create-employee', emp, options)" here whatever the values am sending like firstname those values are shown null in my API i mean those values are set to null when i debug in my APIController
@GurramNavyasri what does your addEmployeeDetails method return?
Whatever the values am sending the same values are returned back, but here it doesnt matter i dont bother about what values it returns but what i am sending those values should be presnent right, but here it doesnt
@GurramNavyasri You are not answering my question. What does your addEmployeeDetails method return inside your code? Can you look to your question and tell me?
But what am asking is not returning values
|
0

same code i have tried with normal controller in same Solution , if i send single parameter values is passed to API controller.

This points to a CORS issue, because if you run 2 solutions with 2 different addresses e.g. localhost:5000/ & localhost:5001/. From my experience this only happens in development.

.net core doc's on CORS: https://learn.microsoft.com/en-us/aspnet/core/security/cors

Try this: to your ServicesConfiguration add

services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                .AllowAnyMethod()
                                                                .AllowAnyHeader())); 

And app.UseCors("AllowAll"); in your Configure

Another thing I spotted is

let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
let options = new RequestOptions({ method: RequestMethod.Post, headers: headers });
let emp = JSON.stringify(obj); 

You are setting content type to application/x-www-form-urlencoded but passing a JSON object.

8 Comments

If i add content type as application/json it is not allowing to call API getting method not allowed
services.AddCors( this should be added to the project from which my call is done or set in the service where my APIController is?
@GurramNavyasri on your API
to my knowledge CORS is used to allow any type of headers,origin,methods. if any of this doesn't satisfy then my API will not be called. But here my API is called but values are becoming null in my object.
@GurramNavyasri I would take a look at the content type, and the object that is being passed. Try to test it with postman.
|
0

WebApiConfig.cs

var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

and my content type as

let headers = new Headers({ 'Content-Type': 'application/json; charset=UTF-8' });

It works...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.