2017-08-04 58 views
2

如何从Angular 4中的PHP文件获取响应?Angular 4 CLI - 从PHP文件获取响应?

如果我将PHP文件放置在资产文件夹中,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它将donwload php文件到磁盘。

如果我将文件放在同一个服务文件夹中,并试图用./test.php调用它,我得到404文件未找到错误。我还获得了404错误,如果我尝试目标与像'./app/services/test.php'的全路径名的文件(我已经尝试了一些其他的变种藏汉)

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], 

项目结构

enter image description here

回答

2

我认为你的PHP文件必须由Apache服务器来处理。 PHP由服务器解释,而不是客户端,这就是为什么你得到脚本的源代码,而不是这个脚本的结果。 所以,你打电话给你的PHP脚本,你在你的控制器做,但看起来像一个URL(或URI):

https://someserver.tld/test.php 

如果“somserver.tld”运行一个正确配置Apache的PHP。您可以尝试使用本地机器上的任何XAMP服务器。

您还需要传递JSON头并打印JSON结果以处理Angular Script中的结果。

希望它有帮助

+0

我试着将文件移动到一个Apache服务器,它的工作就像一个魅力。 WAMP服务器 - >'http:// localhost:8080/php/test.php' - 我还必须包含CORS头标头(“Access-Control-Allow-Origin:*”);' – Henkolicious