Я хочу получить переменную из моего getData.php файл, который находится в папке src / assets углового проекта.
<?php
...
echo json_encode('test');
?>
получить-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
Ваш PHP-файл не будет работать в проекте NodeJS.
Вам нужно отделить ваше Angular App от логики вашего сервера. Используйте Nginx или Apache для обслуживания вашего PHP-файла, тогда вы сможете вызывать его в своей функции getTest ().
Других решений пока нет …