2017-08-04 9 views
2

Angular 4のPHPファイルからの応答を取得するにはどうすればよいですか?Angular 4 CLI - PHPファイルからの応答を取得しますか?

私がassetsフォルダにPHPファイルを置くと、GETリクエストによってファイルが見つけられ、ファイルの内容がダウンロードされます。私はlocalhost:4200/assets/test.phpを参照する場合例えば

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';↵?>" 

また、それは、ディスクへのPHPファイルをdonwloadます。

ファイルを同じサービスフォルダに置き、./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) 
    ); 
    } 
} 

を(私はaswell他のいくつかのバリエーションを試してみました) 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)を持つ:「somserver.tldは」適切に設定されたApache PHPを実行している場合

https://someserver.tld/test.php 

。ローカルマシン上の任意のXAMPサーバーで試すことができます。

JSONヘッダーを渡してJSON結果を出力して、角度スクリプトの結果を処理する必要があります。

希望します。

+0

ファイルをApacheサーバーに移動しようとしましたが、魅力的でした。 WAMPサーバ - > 'http:// localhost:8080/php/test.php' - 私はCORSヘッダ' header( "Access-Control-Allow-Origin:*"); ' – Henkolicious

関連する問題