我使用普通的javascript从php脚本服务器端获取数据,但我想使用angular进行尝试。
此代码获取一个php文件,该文件依次查询数据库(simple select with filter等),并返回一个json文件,供脚本使用,然后显示。
有什么简单的方法可以用角度来做这个吗?
这就是现在的脚本
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注入的影响,它只是一个用于快速查询数据的示例文件,而不是用于生产中)
发布于 2020-07-22 17:59:04
演示 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 || {};
}
}
发布于 2020-07-22 18:08:33
HttpClient提供了执行HTTP请求的HTTP。这个API的响应类型是可观察的类型的RxJS,它有许多内置的方法来处理数据。
您可以按照以下的方式执行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
);
https://stackoverflow.com/questions/63040355
复制相似问题