Angular4: Why does not http request the service?

2
import { Injectable }     from '@angular/core';
import { Http, Headers,Response } from '@angular/http';
import {Observable} from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class LugaresService {
  // private instance variable to hold base url
  private serviceUrl = 'http://127.0.0.1:8080/ProgramaHospitalServicios/service';
  // Resolve HTTP using the constructor
  constructor (private http: Http) {}

    public getLugares(){
    var data:any = {};
    const headers = new Headers({"Content-Type":"application/json"});
    debugger;
    var body:any = {
      "service":"getLugares",
      "params": {}
    };
    this.http.post(this.serviceUrl, body, {headers:headers})
      .map((resultado)=> {
        console.log(resultado);
        debugger;
        data = resultado.json().lugares;
        debugger;
        console.log(data);
      } )
      .catch(this.handleError); // Trouble line.
      return data;
  }  

  public handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }
  public buscarLugar(id){
    console.log(id);
    const headers = new Headers({"Content-Type":"application/json"});
    var body:any = {
      "service":"getLugar",
      "params":  {
                  "id":id
                  }
    };
    this.http.post(this.serviceUrl, body, {headers:headers})
      .map((resultado)=> {
        const data = resultado.json().lugar;
        console.log(data);
        return data;
      })
  }
  public guardarLugar(lugar){
    console.log(lugar);
    const headers = new Headers({"Content-Type":"application/json"});
    var body:any = {
      "service":"putLugares",
      "params": {
                  "nombre": lugar.nombre,
                  "cercania": lugar.cercania,
                  "distancia": lugar.distancia,
                  "descripcion": lugar.descripcion,
                  "plan": lugar.plan
                 }
    };
    this.http.post(this.serviceUrl, body, {headers:headers})
      .map((resultado)=> {
        const data = resultado.json().lugares;
        console.log(data);
        return data;
      })
  }
}

The calling code

import { Component } from '@angular/core';
import { LugaresService } from '../services/lugares.service'

@Component({
  selector: 'app-lugares',
  templateUrl: './lugares.component.html',
  styleUrls: ['./lugares.component.css']
})
export class LugaresComponent {
  title = 'Lugares';
  lat:number = 40.931910;
  lng:number = -4.117217;
  lugares = null; 
  constructor(private lugaresService: LugaresService){
    this.lugares = lugaresService.getLugares()
    .subscribe(lugares=>{
      this.lugares=lugares;
      var me = this;
      me.lugares = Object.keys(me.lugares).map(function (key){return me.lugares[key]});
    }, error=>{
      console.log(error);
    });
  }
}
    
asked by Carlos Guerra Cubillo 07.11.2017 в 11:24
source

3 answers

1

You should try adding a type to your function getLugares to show the compiler with forecast what kind of value it is going to return. For example (because in this case it is an Observable):

public getLugares(): Observable<any>{
  return this.http.post(this.serviceUrl, body, {headers:headers})
    .map((resultado)=> {
      console.log(resultado);
      return resultado.json().lugares;
    }).catch(this.handleError); 
}

Also, is there any reason that you need the observable that would be returned from the 'getLocations' assigned to this.places? This can be problematic despite the variable 'this.sites' has no type and in addition, the value it contains would be erased instantly when the map function is executed. If it were me, I would try like this:

lugaresService.getLugares()
  .subscribe(lugares=>{
    this.lugares=lugares;
    var me = this;
    me.lugares = Object.keys(me.lugares).map(function (key){return 
      me.lugares[key]});
  }, error=>{
    console.log(error);
});
    
answered by 08.11.2017 в 18:57
0

Your method makes the request but returns an empty object because you do not consider that map will be executed asynchronously. Try something like this, returning an Observable:

  public getLugares(){

    const headers = new Headers({"Content-Type":"application/json"});
    debugger;
    var body:any = {
      "service":"getLugares",
      "params": {}
    };
    return this.http.post(this.serviceUrl, body, {headers:headers})
      .map((resultado)=> {
        console.log(resultado);
        return resultado.json().lugares;
      }).catch(this.handleError); 

  }  
    
answered by 07.11.2017 в 12:58
0

places.component.ts

import { Component } from '@angular/core';
import { LugaresService } from '../services/lugares.service';
import {Observable} from 'rxjs';
import 'rxjs/add/observable/throw';
import { trigger, state, style, transition, animate } from '@angular/animations'

@Component({
  selector: 'app-lugares',
  templateUrl: './lugares.component.html',
  animations: [
    trigger('contenedorAnimable', [
       state('inicial', style({
         opacity:0
       })),
       state('final', style({
         opacity:1
       })),
       transition('inicial => final', animate(2000)),
       transition('final => inicial', animate(1000))
      ])
  ]})

export class LugaresComponent {
  title = 'Lugares';
  state = 'inicial';
  lat:number = 40.931910;
  lng:number = -4.117217;
  lugares=[];
  animar(){
    this.state = (this.state === 'final') ? 'inicial' : 'final';
  }
  animacionInicia(e){
    console.log('Iniciado!')
  }
  constructor(private lugaresService: LugaresService){
    lugaresService.getLugares(this);
    this.state = 'final';
   }
}

places.service.ts

import { Injectable }     from '@angular/core';
import { Http, Headers,Response } from '@angular/http';
import {Observable} from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class LugaresService {
  // private instance variable to hold base url
  private serviceUrl = 'http://127.0.0.1:8080/ProgramaHospitalServicios/service';
  // Resolve HTTP using the constructor
  private lugares = [];
  constructor (private http: Http) {}

    public getLugares(parent):any{

    const headers = new Headers({"Content-Type":"application/json"});

    var body:any = {
      "service":"getLugares",
      "params": {}
    };

    this.http.post(this.serviceUrl, body, {headers:headers})
    .subscribe(lugares=>{
        this.lugares=lugares.json();
        var me = this;
        this.lugares=Object.keys(me.lugares)
          .map(function (key){
            return me.lugares[key]
          });
          parent.lugares=this.lugares[0];
    }, err => { 
      return err; 
    });
  }  


  public getLugar(id):any{
    console.log(id);
    const headers = new Headers({"Content-Type":"application/json"});
    var body:any = {
      "service":"getLugar",
      "params":  {
                  "id":id
                  }
    };
    return this.http.post(this.serviceUrl, body, {headers:headers})
      .subscribe(response=>{
        console.log(response.json().lugar[0]);
        return response.json().lugar[0];
    }, err => { 
      console.log("status: " + err.status + ", Error: " + err._body);
      return null;
    });
  }
  public guardarLugar(parent){
    console.log(parent.lugar);

    const headers = new Headers({"Content-Type":"application/json"});
    if (parent.lugar.id=='new'){
    var body:any = {
        "service":"putLugares",
        "params": { 
                  "nombre": parent.lugar.nombre,
                  "descripcion": parent.lugar.descripcion,
                  "calle": parent.lugar.calle,
                  "ciudad": parent.lugar.ciudad,
                  "pais": parent.lugar.pais,
                  "lat": parent.lugar.lat,
                  "lng": parent.lugar.lng,
                  "plan": parent.lugar.plan,
                  "active": parent.lugar.active
                 }
      };
      this.http.post(this.serviceUrl, body, {headers:headers})
       .subscribe(lugar=>{
          parent.lugar=lugar.json();  
          parent.warning = "Se añadió con exito."
      }, err => { 
        console.log("status: " + err.status + ", Error: " + err._body);
        parent.warning = "status: " + err.status + ", Error: " + err._body;
      });
    } else {
      var body:any = {
        "service":"updLugares",
        "params": { 
                  "nombre": parent.lugar.nombre,
                  "descripcion": parent.lugar.descripcion,
                  "calle": parent.lugar.calle,
                  "ciudad": parent.lugar.ciudad,
                  "pais": parent.lugar.pais,
                  "lat": parent.lugar.lat,
                  "lng": parent.lugar.lng,
                  "plan": parent.lugar.plan,
                  "active": parent.lugar.active,
                  "id": parseInt(parent.lugar.id)
                 }
      };
      this.http.post(this.serviceUrl, body, {headers:headers})
       .subscribe(lugar=>{
          parent.lugar=lugar.json();  
          parent.warning = "Se actualizó con exito."
      }, err => { 
        console.log("status: " + err.status + ", Error: " + err._body);
        parent.warning = "status: " + err.status + ", Error: " + err._body;
      });
    }

  }
  public obtenerGeoData(direccion:string){
    return this.http.get('http://maps.google.com/maps/api/geocode/json?address='+direccion);
  }
}
    
answered by 19.11.2017 в 18:44