使用WebApi在Angular中进行CRUD操作

时间:2018-10-17 07:31:19

标签: asp.net-mvc angular

employee.component.ts

import { Component, OnInit } from "@angular/core";
import { EmployeeService } from "../Shared/employee.service";
import { NgForm } from "@angular/forms";
@Component({
  selector: "app-employe",
  templateUrl: "./employe.component.html",
  styleUrls: ["./employe.component.css"]
})
export class EmployeComponent implements OnInit {
  constructor(private employeeService: EmployeeService) {}

  ngOnInit() {
    this.resetForm();
  }

  resetForm(form?: NgForm) {
    if (form != null) form.reset();
    this.employeeService.SelectedEmployee = {
      EmpId: null,
      FirstName: "",
      LastName: "",
      EmpCode: "",
      Position: "",
      Office: ""
    };
  }
  onSubmit(form ?:NgForm){
    this.employeeService.postEmployee(form.value).subscribe(data =>{
       this.resetForm(form);

     
     })
   

  }
}


Employee.service.ts

import { Injectable } from "@angular/core";
import { Employee } from "./employee.model";
import {
  Http,
  Response,
  Headers,
  RequestOptions,
  RequestMethod
} from "@angular/http";
 import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import "rxjs/add/operator/toPromise";
import 'rxjs/add/operator/catch';
import { map } from 'rxjs/operators';
import 'rxjs/add/operator/map';
@Injectable({
  providedIn: "root"
})
export class EmployeeService {
  SelectedEmployee: Employee;
  constructor(private http: Http) {}
  postEmployee(emp : Employee){
    var body = JSON.stringify(emp);
    var headerOptions = new Headers({'Content-Type':'application/json'});
    
    var requestOptions = new RequestOptions({method : RequestMethod.Post,headers : headerOptions});
    return this.http.post('http://localhost:3184/api/Emp',body,requestOptions).map(x => x.json());
  }



}
<form class="emp-form" #employeForm="ngForm" >
  <input type="hidden" name="EmployeeID" #EmployeeID="ngModel" [(ngModel)]="employeeService.SelectedEmployee.EmpID">
  <div class="form-row">
    <div class="form-group col-md-6">
      <input class="form-control" name="FirstName" #FirstName="ngModel" [(ngModel)]="employeeService.SelectedEmployee.FirstName"
        placeholder="First Name" required>
      <div class="validation-error" *ngIf="FirstName.invalid && FirstName.touched">This Field is Required.</div>
    </div>
    <div class="form-group col-md-6">
      <input class="form-control" name="LastName" #LastName="ngModel" [(ngModel)]="employeeService.SelectedEmployee.LastName" placeholder="Last Name"
        required>
      <div class="validation-error" *ngIf="LastName.invalid && LastName.touched">This Field is Required.</div>
    </div>
  </div>
  <div class="form-group">
    <input class="form-control" name="Position" #Position="ngModel" [(ngModel)]="employeeService.SelectedEmployee.Position" placeholder="Position">
  </div>
  <div class="form-row">
    <div class="form-group col-md-6">
      <input class="form-control" name="EmpCode" #EmpCode="ngModel" [(ngModel)]="employeeService.SelectedEmployee.EmpCode" placeholder="Emp Code">
    </div>
    <div class="form-group col-md-6">
      <input class="form-control" name="Office" #Office="ngModel" [(ngModel)]="employeeService.SelectedEmployee.Office" placeholder="Office">
    </div>
  </div>
  <div class="form-row">
    <div class="form-group col-md-8">
      <button [disabled]="!employeForm.valid" type="submit" class="btn btn-lg btn-block btn-info" (click)="onSubmit(employeForm)">
        <i class="fa fa-floppy-o"></i> Submit</button>
    </div>
    <div class="form-group col-md-4">
      <button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(employeForm)">
        <i class="fa fa-repeat"></i> Reset</button>
    </div>
  </div>
</form>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebDemo
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
           config.EnableCors(new EnableCorsAttribute("http://localhost:4200", headers: "*", methods: "*"));
          
    //  methods:'Access-Control-Request-Method',
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

在这里,我尝试在按钮按下时在SqlServer上使用Post Data,它给了我这个错误:

  

无法加载资源:服务器的状态为400(错误请求)   本地主机/:1已从CORS策略阻止从源“ http://localhost:3184/api/Emp”访问“ http://localhost:8080”处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow -Origin标头出现在请求的资源上。

请先帮助我解决,谢谢。我使用了引用enter link description here

3 个答案:

答案 0 :(得分:0)

尝试

 var cors = new EnableCorsAttribute("*", "*", "*");

    config.EnableCors(cors);

答案 1 :(得分:0)

400 Error清楚地表明错误的数据传递到服务器。请检查data服务器是什么,以及从data端传递的Angular

答案 2 :(得分:0)

在您需要允许的网址前添加原始选项:

config.EnableCors(new EnableCorsAttribute(origins: "http://localhost:4200", headers: "*", methods: "*"));

您还可以允许每个这样的网址

config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*"));