Gurram Navya sri
Gurram Navya sri

Reputation: 1

Angular2 api controller call from ts service file

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

Upvotes: 0

Views: 1287

Answers (3)

Gurram Navya sri
Gurram Navya sri

Reputation: 1

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...

Upvotes: 0

Anton Toshik
Anton Toshik

Reputation: 2929

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.

Upvotes: 0

eko
eko

Reputation: 40677

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

Upvotes: 1

Related Questions