I am trying to make a connection of Angularjs2 with the server but I have not been able to, I will place the code of my file "app.ccomponent.ts" to give more explanation:
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { map } from 'rxjs/operator/map';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = "Http";
datos = Object;
constructor(private http: Http){}
ngOnInit(): void {
this.http.get('http://localhost:4200/items.php').map((res: Response) => res.json())
.subscribe(
res => this.datos = res,
err => console.error(err),
() => console.log('Funciona!')
);
}
}
The Http service provider injects it into the main module, so the provider does not appear in this file.
At the point where the "map" operator appears, I have many problems. If I leave the parameter as it is with its parentheses (res: Response), it sends me the following error:
[ts] Argument of type '(res: Response) = > Promise 'is not assignable to parameter of type' (value: Response, index: number) = > Promise. ' Types of parameters 'res' and 'value' are incompatible. Type 'Response' is not assignable to type 'Response'. Two different types with this name exist, but they are unrelated. Property 'body' is missing in type 'Response'.
If I remove the parentheses and leave it as res: Response .. then it throws the following error:
[ts] Can not find name 'res'. any
If I remove the type "Response" as a parameter type and I put "any" as a value or simply remove the parameter type because it lets me compile but in the run it gives me errors. I'm running the app with "ng serve", it shows in the parameter that happened to the "get" function.
My file items.php is as follows:
<?php
// Conectar a MySQL y obtener los valores deseados..
// En este ejemplo se asume que ya tenemos los datos en un array
$json = array(
'campo1' => 'Jose',
'campo2' => 'Miguel',
'campo3' => 'Cabrera'
);
//Enviar headers y el JSON como respuesta
header('Content-Type: application/json');
header('Content-Type: text/html; charset=utf-8');
echo json_encode($json);
? >
My code has changed a lot, that is, I have tried different ways to connect to the server and I have not been able to, specifically I have also followed the examples of these two pages:
bring information from the database with angular 2
Alberto Basalo's website, academia-binaria.com
None of the examples work for me, I do not know what I'm doing wrong. I have not been able to establish a successful connection between angulajs2 and the server.