如何从 Angular 4 中的 PHP 文件获取响应?
如果我将 PHP 文件放在 assets 文件夹中,GET 请求将找到该文件并下载该文件的内容。例如
headers: Headers
ok: true
status: 200
statusText: "OK"
type: 2
url: "http://localhost:4200/assets/php/test.php"
_body: "<?php ↵ echo 'response from php file';↵?>"
此外,如果我浏览 localhost:4200/assets/test.php
,它会将 php 文件下载到磁盘。
如果我将文件放在同一个服务文件夹中并尝试使用 ./test.php
调用它,我会收到 404 文件未找到错误。如果我尝试使用像 './app/services/test.php'
这样的完整路径名来定位文件,我也会收到 404 错误(我也尝试了其他一些变体)
test.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
@Injectable()
export class TestService {
data: any;
constructor(private _http: Http) { }
getTestData() {
return this._http.get('assets/php/test.php') // <-- Here
.subscribe(
(res: Response) => {
this.data = res;
console.log(this.data)
},
(err: Error) => console.log(err)
);
}
}
home.component.ts
import { Component, OnInit } from '@angular/core';
import { TestService } from '../services/test.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
data: any;
constructor(private _testService: TestService) {}
ngOnInit() {
this.data = this._testService.getTestData();
console.log(this.data);
}
}
test.php
<?php
echo 'response from php file';
?>
app.moduel.ts
import { TestService } from './services/test.service';
...
providers: [TestService],
项目结构
最佳答案
我认为您的 PHP 文件必须由 Apache 服务器处理。 PHP 由服务器解释,而不是客户端,这就是为什么你得到脚本的源代码,而不是这个脚本的结果。 因此,您必须像在 Controller 中那样调用 PHP 脚本,但使用如下所示的 URL(或 URI):
https://someserver.tld/test.php
如果“somserver.tld”运行正确配置的 Apache PHP。您可以在本地计算机上尝试使用任何 XAMP 服务器。
您还必须传递 JSON header 并打印 JSON 结果以在 Angular 脚本中处理结果。
希望对你有帮助
关于php - Angular 4 CLI - 从 PHP 文件获取响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45503123/