2017-08-04 21 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