Angular - 如何从本地PHP文件获取变量

时间:2017-09-10 19:05:22

标签: php angular

我想从角项目的src / assets文件夹中的 getData.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 时,我得到了:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

当我将php从echo json_encode('test')更改为echo 'test'并将服务从.map(response => response.json())更改为.map(response => response)时,我就进入了控制台:

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

如何从 php 文件中检索变量?

@ angular / cli:1.4.1
@ angular / core:4.3.6

1 个答案:

答案 0 :(得分:0)

您的PHP文件在NodeJS项目下无法运行。 您需要将Angular App与服务器逻辑分开。使用Nginx或Apache为您的PHP文件提供服务,然后您就可以在getTest()函数中调用它。