2017-09-10 21 views
0

角度プロジェクトのsrc/assetsフォルダにあるgetData.phpファイルから変数を取得したいと思います。角度 - ローカルPHPファイルから変数を取得する方法

<?php 

... 

echo json_encode('test'); 
?> 

のget-data.service

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 

import 'rxjs/add/operator/map'; 

@Injectable() 
export class GetDataService { 

    constructor(private http: Http) {} 

    getTest(): Observable<any> { 
     return this.http.get('assets/getData.php') 
       .map(response => response.json()); 
    } 
} 

app.component

import { Component } from '@angular/core'; 

import { GetDataService } from './services/get-data.service'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 

    constructor(private getDataService: GetDataService) { } 

    title = 'Run Chart Generator'; 
    data; 

    getTestTwo() { 
     this.getDataService.getTest() 
      .subscribe(data => { 
       this.data = data; 
       console.log(this.data) 
      }); 
    } 
} 

は私が呼ぶ機能getTestTwo私が持っている:

Object { _body: "<?php include('simple_html_dom.ph…", status: 200, ok: true, statusText: "OK", headers: Object, type: 2, url: "http://localhost:4200/assets/getDat…" }

は、どのように私は私のから変数を取得することができます。.map(response => response.json()).map(response => response)には、私は、コンソールに持っているから、私はecho json_encode('test')からecho 'test'とサービスにPHPを変更SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data


PHPファイル?角度/ CLI @

:角度/コア@ 1.4.1
:4.3.6

+0

PHP JSONのエンコーディングが正しくないことが判明しました。手動で行うためのメソッドを作成する必要があります。角度のある 'console.log(JSON.stringify(" test "))'を使用し、それを 'json_encode(" test ")'のPHPエコーと比較することをお勧めします。 –

答えて

0

あなたのPHPファイルはNodeJSプロジェクトの下では動作しません。 サーバーロジックから角型アプリケーションを分離する必要があります。あなたのPHPファイルを提供するためにNginxまたはApacheを使用すると、getTest()関数で呼び出すことができます。

関連する問題