2017-06-05 147 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