How to connect Angularjs2 with the server?

2

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.

    
asked by Ricardo Gabriel 08.08.2017 в 00:57
source

1 answer

0

By parts because they are several things. First of all AngularJs 2 does not exist. You say that you are learning why clarify that aspect. One thing is Angular JS. Which are Angular versions 1.X and then Angular (which is what you're using) which are the versions of angular from 2.0 onwards.

That said, I suggest you take a look at a typescript manual. For example when declaring the variables the correct thing would be

title: string;
title = 'Http';

That said, I'll correct a few things in the code to see if we can get it to work.

The imports

import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Http, Response} from '@angular/http';
import 'rxjs/operator/map';
import { Observable }     from 'rxjs/Observable';

As you will see the import of the map is done with import 'rxjs/operator/map'; It is not necessary to put what they had previously. I also add the import of Response .

Export the class and constructor

 export class AppComponent implements OnInit {
    datos: any;


      constructor(private http: Http){}

Here we have changed a couple of things. First the http from the beginning is not necessary since in the constructor you are already declaring a private variable called http . And the variable data. If you do not know what the server returns, we initialize it to any directly and ready.

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!')
    );
  }
 }

In principle, this should work even though I'm not really sure if the .subscribe will work correctly without being inside a observable method.

If it gives you some kind of error, comment it and we look at it.

    
answered by 08.08.2017 в 08:51