Collect JSON from an API with Angular 2

2

I try to pick up the JSON provided by an API that I have created in a service, but I do not receive it for whatever reason.

getLibro(id: string){
    return this._http.get(this.url + 'libros/' + id)
               .map(res => {
                   console.log(res.json()); //No muestra nada
                   return res.json();
               })

However, the getLibros () method does not have problems when collecting the information. Next, the entire service:

import { Injectable } from '@angular/core';

import { Http } from "@angular/http";
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";

@Injectable()
export class LibrosService {

url: string = "http://localhost/API/public/index.php/api/";

constructor(private _http: Http) { }

getLibros(){
    return this._http.get(this.url + 'libros')
                .map(res => res.json());        //recoge el json perfectamene
}

getLibro(id: string){
    return this._http.get(this.url + 'libros/' + id)
               .map(res => {
                   console.log(res.json());     //No muestra nada
                   return res.json();
               })
}

I appreciate the help in advance.

    
asked by Sh13 05.06.2017 в 13:18
source

1 answer

1

Fortunately, they helped me find the solution because the most frustrating of all was that there were no errors on the console. And the problem was not in the service but in the component.

Here is my solution:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { LibrosService } from "app/services/libros.service";
import { Subscription } from "rxjs/Subscription";

@Component({
  selector: 'app-libro',
  templateUrl: './libro.component.html'
})
export class LibroComponent implements OnInit {

  public libro: any =[];
  private sub: Subscription;
  public errorMessage: string;

  constructor( private _activatedRoute: ActivatedRoute,
               private _librosService: LibrosService ) {}

  ngOnInit() {
    this.sub = this._activatedRoute.params
                   .subscribe(params => {
                        let id = +params['id'];
                        this.getLib(id);
                    });
  }

  getLib(id){
      this._librosService.getLibro(id)
          .subscribe(libro => {
              this.libro = libro,
              error => this.errorMessage = <any>error
          });
  }
}

Thanks to everyone who has interested you.

    
answered by 10.06.2017 / 17:33
source