Angular2 api controller call from ts service file

时间:2017-05-16 09:28:12

标签: asp.net angular asp.net-apicontroller

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

  

我在同一个解决方案中尝试使用普通控制器的相同代码,如果我将单个参数值传递给API控制器。

这指向CORS问题,因为如果您运行2个具有2个不同地址的解决方案,例如localhost:5000/&amp; localhost:5001/。根据我的经验,这只发生在开发中。

关于CORS的

.net核心文档: https://docs.microsoft.com/en-us/aspnet/core/security/cors

试试这个:添加到您的ServicesConfiguration

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

配置

中的app.UseCors("AllowAll");

我发现的另一件事是

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

您正在将内容类型设置为application/x-www-form-urlencoded,但会传递JSON个对象。

答案 2 :(得分:0)

WebApiConfig.cs

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

我的内容类型为

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

它有效......