我的api无法正常工作,并且没有显示异常

时间:2018-10-01 17:24:17

标签: php angular typescript api

因此,我正在尝试创建自己的API,但由于某些原因它无法正常工作,并且未显示任何异常,因此我无法理解为什么。

这是我的代码:

enter image description here

数据库页面     

    // specify your own database credentials
    private $host = "**************";
    private $db_name = "***********";
    private $username = "**********";
    private $password = "***********";
    public $conn;

    // get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>

创建页面

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once '../config/database.php';

// instantiate product object
include_once '../object/department.php';

$database = new Database();
$db = $database->getConnection();

$department = new Department($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

// set employee property values
$department->name = $data->name;
$department->location = $data->location;

// create the department
if($department->create()){
    echo '{';
        echo '"message": "Department was created."';
    echo '}';
}

// if unable to create the department, tell the user
else{
    echo '{';
        echo '"message": "Unable to create department."';
    echo '}';
}
?>

删除页面

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");


// include database and object file
include_once '../config/database.php';
include_once '../object/department.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

// prepare department object
$department = new Department($db);

// get department id
// set department id to be deleted
$department->id = isset($_GET['id']) ? $_GET['id'] : die();

// delete the department
if($department->delete()){
    echo '{';
        echo '"message": "Department was deleted."';
    echo '}';
}

// if unable to delete the department
else{
    echo '{';
        echo '"message": "Unable to delete object."';
    echo '}';
}

?>

阅读页面

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Credentials: true");
header('Content-Type: application/json');

// include database and object files
include_once '../config/database.php';
include_once '../object/department.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

// prepare product object
$department = new Department($db);

// set ID property of product to be edited
$department->id = isset($_GET['id']) ? $_GET['id'] : die();

// read the details of product to be edited
$department->readOne();

// create array
$department_arr = array(
    "id" =>  $department->id,
    "name" => $department->name,
    "location" => $department->location


);

// make it json format
print_r(json_encode($department_arr));
?>

阅读页面

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
include_once '../config/database.php';
include_once '../object/department.php';

// instantiate database and employee object
$database = new Database();
$db = $database->getConnection();

// initialize object
$department = new Department($db);

// query products
$stmt = $department->read();
$num = $stmt->rowCount();

// check if more than 0 record found
if($num>0){

    // department array
    $department_arr=array();
    //$department_arr["records"]=array();

    // retrieve our table contents

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        // extract row
        // this will make $row['name'] to
        // just $name only
        extract($row);

        $employee_item=array(
            "id" => intval($id),
            "name" => $name,
            "location" => $location

        );

        array_push($department_arr, $department_item);
    }

    echo json_encode($department_arr);
}

else{
    echo json_encode(
        array("message" => "No departments found.")
    );
}
?>

搜索页面

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
include_once '../config/database.php';
include_once '../object/department.php';

// instantiate database and employee object
$database = new Database();
$db = $database->getConnection();

// initialize object
$department = new Department($db);

// get keywords
$keywords=isset($_GET["s"]) ? $_GET["s"] : "";

// query departments
$stmt = $department->search($keywords);
$num = $stmt->rowCount();

// check if more than 0 record found
if($num>0){

    // employees array
    $department_arr=array();
    //$department_arr["records"]=array();

    // retrieve our table contents
    // fetch() is faster than fetchAll()
    // http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        // extract row
        // this will make $row['name'] to
        // just $name only
        extract($row);

        $employee_item=array(
            "id" => $id,
            "name" => $name,
            "location" => $location

        );

        array_push($department_arr, $department_item);
    }

    echo json_encode($department_arr);
}

else{
    echo json_encode(
        array("message" => "No departments found.")
    );
}
?>

更新页面

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// include database and object files
include_once '../config/database.php';
include_once '../object/department.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

// prepare product object
$department = new Department($db);

// get id of product to be edited
$data = json_decode(file_get_contents("php://input"));

// set ID property of product to be edited
$department->id = $data->id;

// set product property values
$department->name = $data->name;
$department->location = $data->location;


// update the department
if($product->update()){
    echo '{';
        echo '"message": "Department was updated."';
    echo '}';
}

// if unable to update the department, tell the user
else{
    echo '{';
        echo '"message": "Unable to update department."';
    echo '}';
}
?>

部门页面     

    // database connection and table name
    private $conn;
    private $table_name = "departments";

    // object properties
    public $id;
    public $name;
    public $location;



    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }
// read department
function read(){

    // select all query
    $query = "SELECT
                 d.id, d.name, d.location,
            FROM
                " . $this->table_name . " d
            ORDER BY
                d.id";

    // prepare query statement
    $stmt = $this->conn->prepare($query);

    // execute query
    $stmt->execute();

    return $stmt;
}

// read one
function readOne(){

    // query to read single record
    $query = "SELECT
                 d.id, d.name, d.location
            FROM
                " . $this->table_name . " d
            WHERE
                d.id = ?
            LIMIT
                0,1";

    // prepare query statement
    $stmt = $this->conn->prepare( $query );

    // bind id of department to be updated
    $stmt->bindParam(1, $this->id);

    // execute query
    $stmt->execute();

    // get retrieved row
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    // set values to object properties
    $this->name = $row['name'];
    $this->location = $row['location'];

}
function create(){

    // query to insert record
    $query = "INSERT INTO
                " . $this->table_name . "
            SET
                name=:name,location=:location";

    // prepare query
    $stmt = $this->conn->prepare($query);

    // sanitize
    $this->name=htmlspecialchars(strip_tags($this->name));
    $this->location=htmlspecialchars(strip_tags($this->location));



    // bind values
    $stmt->bindParam(":name", $this->name);
    $stmt->bindParam(":location", $this->location);



    // execute query
    if($stmt->execute()){
        return true;
    }

    return false;

}
// delete the department
function delete(){

    // delete query
    $query = "DELETE FROM " . $this->table_name . " WHERE id = ?";

    // prepare query
    $stmt = $this->conn->prepare($query);

    // sanitize

    // bind id of record to delete
    $stmt->bindParam(1, $this->id);

    // execute query
    if($stmt->execute()){
        return true;
    }

    return false;

}
// search department
function search($keywords){

    // select all query
    $query = "SELECT
                 d.id, d.name, d.location
            FROM
                " . $this->table_name . " d
            WHERE
                d.name LIKE ?
            ORDER BY
                d.id ";

    // prepare query statement
    $stmt = $this->conn->prepare($query);

    // sanitize
    $keywords=htmlspecialchars(strip_tags($keywords));
    $keywords = "%{$keywords}%";

    // bind
    $stmt->bindParam(1, $keywords);

    // execute query
    $stmt->execute();

    return $stmt;
}
// update the department
function update(){

    // update query
    $query = "UPDATE
                " . $this->table_name . "
            SET
                name = :name,
                location = :location,

            WHERE
                id = :id";

    // prepare query statement
    $stmt = $this->conn->prepare($query);

    // sanitize
    $this->name=htmlspecialchars(strip_tags($this->name));
    $this->location=htmlspecialchars(strip_tags($this->location));


    // bind new values
    $stmt->bindParam(':name', $this->name);
    $stmt->bindParam(':location', $this->location);


    // execute the query
    if($stmt->execute()){
        return true;
    }

    return false;
}
}

部门服务页面

import { Injectable } from '@angular/core';
import { Departments } from './departments';
import { Department } from './department';
import { Observable, of } from 'rxjs';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Http, Response } from '@angular/http';
@Injectable({
  providedIn: 'root'
})
export class DepartmentService {


    constructor(private http: HttpClient) { }
    dep : Department[] = Departments;
    private depReadOne = 'http://i378011.hera.fhict.nl/api_Web/department/read_one.php?id=';
    private depRead = 'http://i378011.hera.fhict.nl/api_Web/department/read.php';
    private depDelete = 'http://i378011.hera.fhict.nl/api_Web/department/delete.php?id=';
    private depSearch = 'http://i378011.hera.fhict.nl/api_Web/department/search.php?s=';
    private depAdd = 'i378011.hera.fhict.nl/api_Web/department/create.php';

  //  getDepartments(): Observable<Department[]>{
  //    return of (this.dep);
  //  }

  //  getDepartment(id: number): Observable<Department>{
  //    return of (this.dep.find(department => department.id === id));
//    }

    getDep(id:number):Observable<Department>{
      return this.http.get<Department>(this.depReadOne + id);
        }
    getDepByName(name:string) : Observable<Department>{
      return of (this.dep.find(department => department.name === name))
    }

    getDepartmentName(name: string): Observable<Department>{
      return of(this.dep.find(department => department.name === name));
    }

    getDeps():Observable<Department[]>{
    return this.http.get<Department[]>(this.depRead);
    }



    deleteDep(id:number):Observable<Department>{
    return this.http.get<Department>(this.depDelete + id);
    }
    searchDeps(s: string):Observable<Department[]>{
    return this.http.get<Department[]>(this.depSearch + s);
    }




    updateDepartment(newDepartment: Department): void{
        console.log (this.dep);
      let oldDep = this.dep.find(department => department.id === newDepartment.id)
       oldDep = newDepartment;
      console.log (this.dep);
    }

    addDepartment (name:string, location:string): void {
        console.log (this.dep);
        this.dep.push(new Department(name,location));
        console.log (this.dep);
    }


  //  deleteDepartment(department: Department): void{
  //    console.log (this.dep);

         this.dep.forEach( (item, index) => {
       if(item === department) this.dep.splice(index,1);});
        console.log (this.dep);
    }

  }

我得到的只是浏览器中的空白页面,没有任何异常显示。当我单击鼠标右键并检查时,得到以下信息: enter image description here

1 个答案:

答案 0 :(得分:0)

错误消息非常清楚。在部门服务页面的最后,您致电this.dep.forEach,但是this.dep是未定义的。 在顶部,您调用dep : Department[] = Departments;(通常在构造函数中执行此操作)。如果将此代码移到构造函数中,则可能会起作用,否则应检查从import { Departments } from './departments';

导入的内容