2017-06-17 64 views
1

我有一個簡單的Rails5 API,我試圖在我的Angular應用程序中從API獲取數據。Angular http.get沒有獲取數據

首先,如果我訪問:http://localhost:3000/movies我得到這樣的結果:

[{ 「ID」:2, 「稱號」: 「蝙蝠俠」, 「CREATED_BY」: 「1」, 「created_at」 :「2017-06-17T07:19:35.000Z」,「updated_at」:「2017-06-17T07:19:35.000Z」}]

所以Rails方面的工作。

以我app.component.ts我導入:

import { AppService }   from "./app.service"; 
import { Movie }    from './movie'; 

movie.ts

export class Movie{ 
    id: number; 
    title: string; 
} 

app.service.ts

進口{注射}從 '@角/芯'; 從'@ angular/http'導入{Http,Response};

import { Observable }   from 'rxjs/Observable'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/map'; 

import { Movie }    from './movie'; 

@Injectable() 
export class AppService{ 

    private moviesUrl = 'http://localhost:3000/movies'; 

    constructor(private http: Http){ 

    } 

    getMovies(): Observable<Movie[]>{ 
    return this.http.get(this.moviesUrl) 
     .map(this.extractData) 
     .catch(this.handleError); 
    } 

    private extractData(res: Response){ 
    let body = res.json(); 
    return body.data || {}; 
    } 

    private handleError (error: Response | any) { 
    // In a real world app, you might use a remote logging infrastructure 
    let errMsg: string; 
    if (error instanceof Response) { 
     const body = error.json() || ''; 
     const err = body.error || JSON.stringify(body); 
     errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
    } else { 
     errMsg = error.message ? error.message : error.toString(); 
    } 
    console.error(errMsg); 
    return Observable.throw(errMsg); 
    } 

} 

最後我app.component.ts

import { Component }   from '@angular/core'; 
import { AppService }   from "./app.service"; 
import { Movie }    from './movie'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'], 
    providers: [AppService] 
}) 

export class AppComponent { 
    title = 'app works!'; 
    errorMessage: string; 
    movies: Movie[]; 
    mode = 'Observable'; 

    constructor(private appService: AppService){} 

    ngOnInit(){ 
    this.getMovies(); 
    console.log(this.movies); 
    } 

    getMovies(){ 
    this.appService.getMovies() 
     .subscribe(
     movies => this.movies = movies, 
     error => this.errorMessage = <any>error); 
    } 
} 

當我在我的瀏覽器訪問http://localhost:3000/movies我得到了我的彪馬日誌如下:

開始GET 「/電影」 爲127.0.0.1在2017-06-17 10:35:00 +0200 通過MoviesController處理#索引爲HTML 影片加載(1.0ms)選擇movies。*從movies 在6ms內完成200 OK(查看:4.0ms | ActiveRecord的:1.0ms的)

當我訪問http://localhost:4200/在我的角度應用程序,我得到

開始於2017年6月17日10時37分59秒GET爲127.0.0.1 「/電影」 + 0200 處理由MoviesController#指數HTML 電影負荷(0.5毫秒)選擇movies * FROM movies 完成200 OK在4毫秒(瀏覽次數:2.8ms | ActiveRecord的:爲0.5ms)。

因此,Angular應用程序向API發出請求並且API返回結果,但該結果不會顯示在Angular組件中。

+1

你沒有得到在'的console.log任何數據(this.movi​​es) '在'ngOnInit()'中調用,對吧? – Abrar

+4

[我如何從angular2中的Observable/http/async調用返回響應?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from- an-observable-http-async-call-in-angular2) – echonax

+1

@Abrar正確。所以是的,也許http.get確實接收到數據,但Angular先不執行'this.getMovies'函數,並且在ngOnInit中完成'console.log'時? –

回答

0

在Angular中,我們使用從rxjs/Observable導入的Observable來處理異步代碼。

請注意,當您撥打this.appService.getMovies()返回Observable<Movie[]>時,這實質上是一個異步操作。在AppComponentsubscribe它並得到值異步

通知的AppComponent碼 -

export class AppComponent { 
    title = 'app works!'; 
    errorMessage: string; 
    movies: Movie[]; 
    mode = 'Observable'; 

    constructor(private appService: AppService){} 

    ngOnInit(){ 
    this.getMovies(); 
    console.log(this.movies); <--- the value is not set to this.movies yet since data is loading asynchronously 
    } 

    getMovies(){ 
    this.appService.getMovies() 
     .subscribe(
     (movies) => { 
       this.movies = movies; 
       console.log(this.movies); <--- the value will be set here properly 
     }, 

     (error) => { 
       this.errorMessage = <any>error); 
     } 
    } 
} 

希望這有助於。

EXTRA

有關更多閱讀可觀察

+2

答案不是必須的,問題其實是重複的 –