如何在角度7中从数据库中获取数据?

时间:2019-06-04 07:15:03

标签: php angular fetch angular7

在使用PHP fetch API从数据库中获取数据时,我遇到了麻烦。 下面的PHP fetch API与react App可以正常工作,但是使用angular获取时会出错。 这是我使用PHP fetch API的完整代码。

app.component.ts

import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
   constructor(private httpClient: HttpClient){}
  name = 'My App';
 students:any = [];
  baseUrl='http://veomit.com/test/zend/api/fetch.php';
  get_products(){
        this.httpClient.get(this.baseUrl).subscribe((res :{})=>{
        console.log(res);
        this.students = res;
        });
    }
}

app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>
<button (click)="get_products()">GET Data</button>
<ul>
      <li *ngFor="let student of students" >
        userId: {{student.name}}
        Hellotitle: {{student.department}}
        body: {{student.marks}}
      </li>
    </ul> 

php fetch API-fetch.php

<?php 

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Request-Headers: GET,POST,OPTIONS,DELETE,PUT");
$con = mysqli_connect("mysql1004.mochahost.com","a310387_task_for","task_force","a310387_task_force");
$ar=array();

     $query=mysqli_query($con,"select * from student");
     while ($rows=mysqli_fetch_array($query)) {
        $ar[]=$rows;
     }
 echo json_encode($ar);

 ?>
```
Below is my console error:

    HttpErrorResponse {headers: {…}, status: 0, statusText: "Unknown Error", url: "http://veomit.com/test/zend/api/fetch.php"…}
    error: ProgressEvent
    isTrusted: true
    __proto__: ProgressEvent
    headers: HttpHeaders
    headers: Array[0]
    lazyUpdate: null
    normalizedNames: Array[0]
    __proto__: HttpHeaders
    message: "Http failure response for http://veomit.com/test/zend/api/fetch.php: 0 Unknown Error"
    name: "HttpErrorResponse"
    ok: false
    status: 0
    statusText: "Unknown Error"
    url: "http://veomit.com/test/zend/api/fetch.php"
    __proto__: HttpErrorResponse

1 个答案:

答案 0 :(得分:-1)

plz首先从此命令生成服务 ng g服务service_name 然后构造一个函数-

 getAllData(url, headerData = {}){
    const getUrl = this.apiUrl + url;
    //let header:any={'authtoken':this.token};
    return this.http.get(getUrl, { headers: headerData })
    .map(result => result)
    .catch(this.handleError)
  }

然后在应用componen.ts中

get_product(){

 this.service_name.getAllData(this.url).subscribe(
   (response: any) => {

      if (response.status == true) {
      
      } else {
       
      }
    });
}