【发布时间】:2022-01-10 12:46:09
【问题描述】:
我有一个简单的项目并决定开始学习 ionic,我试图从远程 sql server 获取数据。
PHP API 后端 (getData.php)
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Method: POST, GET, DELETE, PUT, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: token, Content-Type');
header('Access-Control-Max-Age: 1728000');
header('Content-Length: 0');
header('Content-Type: text/plain');
$con = mysqli_connect("localhost", "root", "", "dataapi") or die('could not connect DB');
$data = array();
$q = mysqli_query($con, "SELECT * FROM `tbl_data`");
while ($row = mysqli_fetch_object($q)) {
$data[] = $row;
}
echo json_encode($data);
echo mysqli_error($con);
服务 API (api.service.ts)
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
headers: HttpHeaders;
constructor(public http: HttpClient) {
this.headers = new HttpHeaders();
this.headers.append("Accept", 'aplication/json');
this.headers.append("Content-Type", 'aplication/json');
this.headers.append("Access-Control-Allow-Origin", '*');
}
getDatas() {
return this.http.get('https://myweb/getData.php');
// return this.http.get('http://localhost/phpapi/getData.php');
}
}
应用模块(app.module.ts)
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
bootstrap: [AppComponent],
})
export class AppModule {}
调试页面ts(debug.page.ts)
import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/app/api.service';
@Component({
selector: 'app-debug',
templateUrl: './debug.page.html',
styleUrls: ['./debug.page.scss'],
})
export class DebugPage implements OnInit {
datas: any = [];
constructor(public _apiService: ApiService) {
this.getDatas();
}
getFoods() {
this._apiService.getDatas().subscribe((res:any) => {
console.log("SUCCESS ===", res);
this.datas = res;
},(error:any) => {
console.log("ERROR===", error);
})
}
调试页面 html (debug.page.html)
<ion-item lines="inset" *ngFor="let data of datas">
<ion-label>
<p>Name: {{data.name}}</p>
<p>Rating: {{data.rating}}</p>
<p>Category: {{data.categories}}</p>
</ion-label>
第一个问题: 它在 localhost(我使用 xampp)上运行良好,但在远程主机上运行良好
console log : SUCCESS === null
当我设置错误的数据库用户或密码时,会出现此控制台日志成功 === null。
第二个问题: 在 localhost 上的“工作”部分不能在 android 设备上工作,只能在浏览器上工作。已经尝试使用本地 IP 而不是 localhost 解决。
【问题讨论】: