使用Angular 2从API获取JSON数据

时间:2017-06-05 14:02:20

标签: json angular

我正在尝试通过我创建的API获取一些JSON数据,但它没有收到它。我使用了以下Angular代码:

getBook(id: string){
    return this._http.get(this.url + 'books/' + id)
               .map(res => {
                   console.log(res.json());         //It does not show anything
                   return res.json();
               })

然而 getBooks()方法在获取数据方面没有问题。浏览器控制台中没有错误。 这是整个服务代码:

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) { }

getBooks(){
    return this._http.get(this.url + 'books')
                .map(res => res.json());        //it works
}

getBook(id: string){
    return this._http.get(this.url + 'books/' + id)
               .map(res => {
                   console.log(res.json());     //it does not work
                   return res.json();
               })
}

对不起我的英语,如果不是很好,谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

在服务中

getHeroes(): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

在组件

getHeroes() {
    this.heroService.getHeroes()
                     .subscribe(
                       heroes => this.heroes = heroes,
                       error =>  this.errorMessage = <any>error);
  }

答案 1 :(得分:0)

幸运的是,一位朋友帮助我找到了解决方案,因为最令人沮丧的是控制台没有显示任何错误。问题不在于服务,而是在组件中。

这是我的解决方案:

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

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

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

  constructor( private _activatedRoute: ActivatedRoute,
               private _booksService: BooksService ) {}

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

  getBok(id){
      this._booksService.getBook(id)
          .subscribe(book => {
              this.book = book,
              error => this.errorMessage = <any>error
          });
  }
}

感谢各位的帮助。