首页 > 解决方案 > 如何从 API 获取员工信息?

问题描述

所以我有我的部门表,我应该在其中显示有关在那里工作的员工的一些信息

在此处输入图像描述

这是我的代码:

<div class="main">
<div  class = "details" *ngIf="department">

  <h2 ><span class="name">{{department.name }} {{department.location}}</span>  Details </h2>

      <div class="container">
<div> <span >id: </span>{{department.id}}</div>
         <p>Department name:
           <input [(ngModel)]="department.name" placeholder="name" class="Form"/>
          </p>
       <br>
          <p>Location:
            <input [(ngModel)]="department.location" placeholder="location" class="Form"/>
          </p>
       <br>

      <p> Employee:
       <select [(ngModel)]="department.employee"  class="Form">
         <option *ngFor="let employee of employees" value="{{employee.firstname}}">{{employee.firstname}}</option>
       </select>
     </p>
 </div>

 <div *ngIf="average">
 <button class="showDetails" (click) = "Show()">Show Employee Details</button>
 </div>

 <div *ngIf="emp">
   <p *ngIf="emp" class="emp"> Employee id: {{ emp.id}} </p>
   <p *ngIf="emp" class="emp"> Employee name: {{emp.firstname}}   {{employee.lastname}}   </p>
  <p *ngIf="emp" class="emp"> Employee gender: {{emp.gender}} </p>
  <p *ngIf="emp" class="emp"> Employee age: {{emp.age}} </p>
   <button class="delete" (click) = "Delete()">Hide</button>
 </div>


<div>
<span class = "backbtn">
                    <button class="btn" (click) = "goBack()">Back</button>
                    </span>
                    <span class = "addbtn">
                    <button class="btn" (click)="save()">Update</button>
 </span>
</div>
</div>


__
</div>

这里是实际的方法:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { Department } from '../department';
import { Employee } from '../employee';
import { DepartmentService }  from '../department.service';
import {Observable} from 'rxjs';
import { EmployeeService }  from '../employee.service';
@Component({
  selector: 'app-department-detail',
  templateUrl: './department-detail.component.html',
  styleUrls: ['./department-detail.component.css']
})
export class DepartmentDetailComponent implements OnInit {

  department : Department ;
  employees: Employee[];
  emp: Employee;
  average:number=1;


  constructor(private route: ActivatedRoute, private employeeService: EmployeeService, private location: Location, private departmentService: DepartmentService) { }

  ngOnInit() {
    //this.getEmployee();
    this.getEmployees();
    this.getDepartment();
  }

  getEmp(): void {
    const id = +this.route.snapshot.paramMap.get('id');
    this.employeeService.getEmp(id).
    subscribe(data => this.emp = data);
  }

  getDepartment(): void{
    const id = +this.route.snapshot.paramMap.get('id');
    this.departmentService.getDepartment(id).
    subscribe(data => this.department = data);
  }

  goBack(): void{
    this.location.back();
  }
  save(): void {
   this.departmentService.updateDepartment(this.department).subscribe();
   this.goBack();
 }
  getEmployees(): void {
    this.employeeService.getEmps().
    subscribe(employees => this.employees = employees);
  }
  Select(firstname:string){
   if(!firstname){ return; }
firstname = firstname.trim();
   this.employeeService.getEmployeeByName(firstname).subscribe(e => this.emp= e);
 }

  Delete():void{
    this.emp = null;
    this.average = 1;
  }
  Show():void{
    this.Select(this.department.employee);
    this.average = null;
  }
}

我相信我的问题出在 getEmployees 方法中,但我不知道如何更改它以使其工作。它曾经在 API 之前工作,但现在它不起作用。提前致谢

import { Injectable } from '@angular/core';
import { Employees } from './mock-employees';
import { Employee } from './employee';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
//import {Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';

const httpOptions = {
     headers: new HttpHeaders({
     'Content-Type':  'application/json',
     'Authorization': 'my-auth-token'
    })
};

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private http: HttpClient) {}


  emp : Employee[] = Employees;
  private empReadOne = 'http://*******.hera.fhict.nl/api_Web/employee/read_one.php?id=';
  private empRead = 'http://*******.hera.fhict.nl/api_Web/employee/read.php';
  private empDelete = 'http://*******.hera.fhict.nl/api_Web/employee/delete.php?id=';
  private empSearch = 'http://*******.hera.fhict.nl/api_Web/employee/search.php?s=';
  private empAdd = 'http://*******.hera.fhict.nl/api_Web/employee/create.php';
  private empUpdate = 'http://*******.hera.fhict.nl/api_Web/employee/update.php';


  getEmp(id:number):Observable<Employee>{
  return this.http.get<Employee>(this.empReadOne + id);
  }
  deleteEmp(id:number):Observable<Employee>{
  return this.http.get<Employee>(this.empDelete + id);
  }
  getEmps():Observable<Employee[]>{
  return this.http.get<Employee[]>(this.empRead);
  }
  searchEmps(s: string):Observable<Employee[]>{
  return this.http.get<Employee[]>(this.empSearch + s);
  }
  putEmps(emp: Employee):Observable<any>{

  return this.http.post(this.empUpdate,emp,httpOptions);
  }
  postEmps(fname: string, lname: string, age: number, gender: string, department: string ):Observable<any>{

  return this.http.post(this.empAdd,{
        "firstname": fname,
        "lastname": lname,
        "age": age,
        "gender": gender,
        "department": department},
        httpOptions);
  }
  getEmployeeByName(firstname:string) : Observable<Employee>{
  // return of (this.emp.find(employee => employee.firstname === firstname))
   return this.http.get<Employee>(this.empRead)
  }
}

标签: angularapi

解决方案


要对此进行调试,您可以查看 HTTP 调用的结果。首先检查浏览器的网络选项卡,HTTP 响应是什么?如果是 200 则正常,如果是 4xx 或 500 则表示正在发送的数据有问题或服务器端出错。

要调试 API 返回的值,只需执行以下操作:

getEmp(): void {
  const id = +this.route.snapshot.paramMap.get('id');
  this.employeeService.getEmp(id).
  subscribe(data => {
    this.emp = data
    console.log('emp', this.emp)
  });
}

并检查您的浏览器控制台以查看响应是否符合预期。

也值得这样做:

const id = +this.route.snapshot.paramMap.get('id');
console.log('id', id);

检查一切是否符合预期。


推荐阅读