How do I get the response from a PHP file in Angular 4?
If i place the PHP file in the assets folder, the GET request will find the file and it will download the content of the file. E.g
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';↵?>"
Also if I browse localhost:4200/assets/test.php it will donwload the php file to disk.
If I place the file in the same service folder and try to call it with ./test.php I get the 404 file not found error. I also get the 404 error if I try to target the file with the full path name like './app/services/test.php' (I've tried a few other variants aswell)
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],
Project structure
