2017-06-17 61 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

答案不是必须的,问题其实是重复的 –