简体   繁体   English

ts服务文件中的Angular2 API控制器调用

[英]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) 我有两个解决方案1. ASP.NET Web应用程序(.Net框架)(Web Api)2. ASP.NET Core应用程序(.Net核心)

in Visula Studio 17. 在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 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 Employee.ts文件

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

Api Employee class file Api员工课程文件

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 我的html文件

<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. 我的ts文件在解决方案中,我的api在另一个解决方案中。 here am getting calls to my API but emp values are all null. 这里正在调用我的API,但是emp值全为空。 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. 如果我将单个参数值发送给API控制器,则在同一解决方案中使用普通控制器尝试过的相同代码。

Thanks in advance 提前致谢

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 在你的情况,如果你使用.toPromise(),你应该使用then

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

Check your network tab to see if you are actually making the request: 检查您的网络标签,查看您是否确实在发出请求: 在此处输入图片说明

In your network tab when you click your button you should see a post request. 在您的网络标签中,点击按钮后,您应该会看到发布请求。

Then check your request: 然后检查您的请求: 在此处输入图片说明

Link of the plunker I used: http://plnkr.co/edit/HR8l5kYlar4XxmgxLa9Z?p=preview 我使用的pl车的链接: http ://plnkr.co/edit/HR8l5kYlar4XxmgxLa9Z?p=preview

same code i have tried with normal controller in same Solution , if i send single parameter values is passed to API controller. 如果我将单个参数值发送给API控制器,则在同一解决方案中使用普通控制器尝试过的相同代码。

This points to a CORS issue, because if you run 2 solutions with 2 different addresses eg localhost:5000/ & localhost:5001/ . 这指出了CORS问题,因为如果您使用2个不同的地址(例如localhost:5000/localhost:5001/运行2个解决方案。 From my experience this only happens in development. 根据我的经验,这仅在开发中发生。

.net core doc's on CORS: https://docs.microsoft.com/en-us/aspnet/core/security/cors CORS上的.net核心文档: https : //docs.microsoft.com/zh-cn/aspnet/core/security/cors

Try this: to your ServicesConfiguration add 试试这个:在您的ServicesConfiguration中添加

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

And app.UseCors("AllowAll"); 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. 您正在将内容类型设置为application/x-www-form-urlencoded但传递了JSON对象。

WebApiConfig.cs 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... 有用...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM