2017-06-05 152 views
0

我想通过API创建一些JSON数据,但它没有收到它。我用下面的代码角:从API获取JSON数据与Angular 2

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(); 
       }) 
} 

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

+0

您是否订阅了可观察的?换句话说,如果你只是附加一个.subscribe()到getBook get,那它会执行吗? – JSess

+0

是的,我在订阅它,但它没有收到数据。 – Sh13

回答

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

感谢大家的帮助。

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); 
    } 
+0

它也行不通。谢谢你的帮助。 – Sh13

+0

你会得到什么错误? –

+0

它不显示错误 – Sh13