Although you could connect directly from Angular2, it represents a bad practice, since it involves exposing the database to the client. The method you mention, connecting to an intermediate server is the preferred one.
In order to do the request , the PHP script must be hosted on a web server (even if it is inside the same machine). That way, <la url>
will be the URL where your script is, either in http://localhost/xxxx/tu_script.php
or where it is hosted.
Code
Broadly speaking, and only by way of example
From Angular2
import {Http, Response} from 'angular2/http';
class Componente {
data: Object;
constructor(private http: Http) {
http.get('http://localhost/xxxx/tu_script.php') //usar la url que corresponda
.map((res: Response) => res.json())
.subscribe(
res => this.data = res,
err => console.error(err),
() => console.log('Funciona!')
);
}
}
In PHP
<?php
//Conectar a MySQL y obtener los valores deseados..
// En este ejemplo se asume que ya tenemos los datos en un array
$json['query_de_bd'][] = array(
'campo1' => 'valor1',
'campo2' => 'valor2',
'etc' => '...'
);
//Enviar headers y el JSON como respuesta
header('Content-Type: application/json');
header('Content-Type: text/html; charset=utf-8');
echo json_encode($json);
?>