如何在角度2中将Id值输入到删除函数中

时间:2017-06-11 16:21:30

标签: angular

我有一个角度应用程序,我试图使用该数据的id删除表行数据。但是我无法将id传递给delete函数。当我尝试这个时,我得到了未定义。如何将id值转换为角度函数。如何在服务中调用带有id的删除功能?

组件:

import { Component } from '@angular/core';
import { Observable} from 'rxjs';
import { FormsModule } from '@angular/forms';

import { Employee } from './employee';
import { EmployeeService} from './employee.service';

@Component({
    selector: 'employee-form',
    templateUrl: './employee-form.component.html',
    styleUrls: ['./employee-form.component.css']
})

export class EmployeeFormComponent{
    employees : Employee[];
    errorMessage : String;
    id : number;
    firstName : String;
    lastName  : String;
    EmployeeType : String;
    employee = new Employee();
    clicked = false;
    constructor(private employeeservice : EmployeeService){}
    ngOnInit(): void{
        this.fetchEmployees();
    }
        fetchEmployees(): void{
            this.employeeservice.getDetailsFromJson()
            .subscribe( employees => this.employees = employees,
                                    error => this.errorMessage = <any>error)
        }

        addEmployee(): void{
            this.employeeservice.addEmployees(this.employee)
            .subscribe(employee => {
                this.fetchEmployees();
                    this.reset();
                    this.firstName = employee.firstname;
                    this.lastName = employee.lastname;
                    this.EmployeeType = employee.employeetype;
                    this.clicked = false;
                    console.log(this.employee.id)
            }, 
            error => this.errorMessage = <any>error);
        }
        deleteEmp(id): void {
                this.employeeservice.delete(id)
                 if (confirm("Are you sure you want to delete " + this.id + "?")){
                console.log();
            }
        }

        private reset(){
            this.employee.firstname = null; 
            this.employee.lastname = null;
            this.employee.employeetype = null;
        }

}

模板:

<h3>Employee Details</h3>
<div class="container"> 
  <div>
    <table class="table table-stripped table-bordered">
      <tr><th>Id</th><th>Firstname</th><th>Lastname</th><th>EmployeeType</th><th>Actions</th></tr>
      <tr *ngFor="let employee of employees">
        <td>{{employee.id}}</td>
        <td>{{employee.firstname}}</td>
        <td>{{employee.lastname}}</td>
        <td>{{employee.employeetype}}</td>
        <td><button class="btn btn-default" (click)="deleteEmp(employee.id); $event.stopPropagation()">Delete</button>
            <button class="btn btn-default" (click)="updateEmp(); $event.stopPropagation()"> Update</button>
        </td>
      </tr>
    </table>
  </div>
  <div>
    <div [hidden]="submitted">
<div class="container" >
    <h1>Employee Form</h1>
    <form class="form-horizontal" (ngSubmit) = "addEmployee()" #employeeform="ngForm">
      <div class="form-group ">
        <label for="firstname" class="control-label col-md-3">FirstName:</label>
        <div class="col-md-6">
        <input type="text" class="form-control col-md-6" id="firstname" required [(ngModel)]="employee.firstname" name="firstname" >


      </div>
      </div>
      <div class="form-group">
        <label for="lastname" class="control-label col-md-3">LastName:</label>
        <div class="col-md-6">
        <input type="text" class="form-control" id="lastname" required [(ngModel)]="employee.lastname" name="lastname">

        </div>
      </div>

      <input type="submit" class="btn btn-success "  [disabled]="!employeeform.form.valid" value="submit">


    </form>
    </div>
    </div>

服务:

import { Injectable } from '@angular/core';
import { Http, Response,Headers,RequestOptions} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import {Employee} from './employee'

@Injectable()
    export class EmployeeService {
            empurl = 'api/employees';
            constructor (private http:Http){}
            getDetailsFromJson():Observable<Employee[]>{
                return this.http.get(this.empurl)
                        .map(this.extractData)
                        .catch(this.HandleErrorObservable);                        
            }
            addEmployees(employee: Employee): Observable<Employee>{
                let headers = new Headers({'Content-Type': 'application/json'});
                let options = new RequestOptions({headers: headers});
                return this.http.post(this.empurl,employee,options)
                        .map(this.extractData)
                        .catch(this.HandleErrorObservable)
            }
            delete(id : number){
                console.log(id);
    return this.http.delete(`${this.empurl}/${id}}, options`)
        .map(res => res.json())
      .catch(this.HandleErrorObservable);
  }

            private extractData(res: Response){
                let body= res.json();
                return body.data || {}
            }
            private HandleErrorObservable(error : Response | any){
                console.log(error.message || error);
                return Observable.throw( error.message || error);
            }
    }

这是调用删除功能的正确方法吗?

1 个答案:

答案 0 :(得分:0)

HTML

<button class="btn btn-default" (click)="deleteEmp(employee.id); $event.stopPropagation()">Delete</button>

组件

deleteEmp(id): void {
         if (confirm("Are you sure you want to delete " + id + "?")){
            this.employeeservice.delete(id).subscribe((res) => console.log(res));
         }

        }

希望它有所帮助!!