bring information from the database with angular 2

2

I am new at angle 2, use a little angular 1x for a university project.

My question is with angle 2, can you bring information from the database?

For example of a database in MySQL but my question is how. In angular 1 I made a php script that made a query to the database but in

asked by Sergio Romero 24.07.2016 в 07:48
source

3 answers

4

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);
?>
    
answered by 24.07.2016 / 16:12
source
3

To bring data to Angular 2 from a MySQL database, I recommend using the following.

  • Use the services from Angular 2 > to make requests to an API RESTFul .

  • Create on the server side API RESTFul , that they receive and return data of JSON type for a better speed of data transfer and so that you can process them in the view of Angular 2 correctly.

  • I recommend using Express with Node JS .

See an example of how to make a request and print the data in the view.

Angular HTTP Request 2

    
answered by 19.01.2017 в 22:56
2

If the technique is the same, although of course the code differs to be TypeScript, since angular 2 has the http to invoke a service that returns json

If you analyze the documentation

link

You'll see that when you create the service, you import

import { Http, Response } from '@angular/http';

It is by means of this that you will invoke the service using http.get which will return an observable (it would be the equivalent to the promice)

    
answered by 24.07.2016 в 08:00