Angular 4 CLI - get response from PHP file?

How to get response from PHP file in Angular 4?

If I put the PHP file in the assets folder, the GET request finds the file and it downloads the contents of the file. For example,

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 download the php file to disk.

If I put a file in the same service folder and try to call it with ./test.php

, I get a 404 not found error. I also get a 404 error if I try to target a file with a fully qualified pathname, for example './app/services/test.php'

(I also tried several other options)

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

enter image description here

+3


source to share


1 answer


I think your PHP file should be processed by the Apache server. PHP is interpreted by the server, not the client, so you get the script's source code, not the results of that script. Thus, you have to call your PHP script the same as in your controller, but with a URL (or URI) that looks like this:

https://someserver.tld/test.php

      

If "somserver.tld" starts a properly configured Apache PHP. You can try with any XAMP server on your local machine.



You also have to pass JSON headers and print the JSON results to process the results in Angular script.

Hope it helps

+2


source







All Articles