簡體   English   中英

使用 angular 從服務器端 php 文件中獲取 json 數據?

[英]Fetching json data from server-side php file with angular?

我正在使用普通的 javascript 從服務器端的 php 腳本中獲取數據,但我想使用 angular 進行嘗試。

此代碼獲取 php 文件,該文件依次查詢數據庫(帶有過濾器的簡單 select 等)並返回 json 文件以供腳本使用,然后顯示。

有沒有一種簡單的方法可以用 angular 做到這一點?

這是現在的腳本

fetch('service/select.php')
.then(function(response) {
    return response.json();
})
.then(function(data) {
    //do something with the data
});

這是它獲取的 php 文件:

<?php
require_once("config.php");
    mysqli_set_charset($con, 'utf8mb4');
    mysqli_query($con, "SET NAMES 'utf8mb4'");
    $rs = mysqli_query($con, "select * from names");
    while($row = mysqli_fetch_assoc($rs)) {
        $res[] = $row;
    }
    echo json_encode($res, JSON_UNESCAPED_UNICODE);
?>

(我知道 php 文件容易被 sql 注入,它只是一個快速查詢數據的示例文件,沒有在生產中使用)

演示HTTPClient模塊是您的需要

import {Injectable} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json'
    })
};
@Injectable()
export class DataService{
    constructor(private http:HttpClient){  }
    
    Post(url:string,body:any): Observable<any>{
        return this.http.post<any>(url, body, httpOptions).pipe( retry(1), catchError(this.handleError) );
    }
    Get(url:string): Observable<any>{
        return this.http .get<any>(url, httpOptions).pipe( retry(1), catchError(this.handleError) );
    }
    private handleError(error: any){
        let body = error.json();     
        return body || {};
    }
}

Angular 提供HttpClient API 做 HTTP 請求。 這個 API 的響應類型是 RxJS 的Observable類型,它有很多內置的方法來處理你的數據。

您可以按照 angular 方式執行 HTTP 請求代碼,而不是獲取API。

const url = 'service/select.php';
const hdrs = new HttpHeaders({ 'Accept': accept ? accept : 'application/json; charset=utf-8' });
this.http.get(url, { headers: hdrs, observe: 'body', responseType: 'json'})
.subscribe(
  data => // do whatever you want to do your data
  err => // get the error response here
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM