如何從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],
項目結構
我試着將文件移動到一個Apache服務器,它的工作就像一個魅力。 WAMP服務器 - >'http:// localhost:8080/php/test.php' - 我還必須包含CORS頭標頭(「Access-Control-Allow-Origin:*」);' – Henkolicious