简体   繁体   English

Angular http.get没有获取数据

[英]Angular http.get not getting data

I have a simple Rails5 API and I'm trying to get data from the API in my Angular application. 我有一个简单的Rails5 API,我试图从我的Angular应用程序中的API获取数据。

First of, if I visit: http://localhost:3000/movies I get this result: 首先,如果我访问: http:// localhost:3000 / movies我得到这个结果:

[{"id":2,"title":"Batman","created_by":"1","created_at":"2017-06-17T07:19:35.000Z","updated_at":"2017-06-17T07:19:35.000Z"}] [{ “ID”:2 “标题”: “蝙蝠侠”, “CREATED_BY”: “1”, “created_at”: “2017-06-17T07:19:35.000Z”, “的updated_at”:“2017-06- 17T07:19:35.000Z“}]

So the Rails side works. 所以Rails方面有效。

In my app.component.ts I import: 在我的app.component.ts导入:

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

movie.ts movie.ts

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

app.service.ts app.service.ts

import { Injectable } from '@angular/core'; 从'@ angular / core'导入{Injectable}; import { Http, Response } from '@angular/http'; 从'@ 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);
  }

}

And finally my app.component.ts 最后是我的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);
  }
}

When I visit http://localhost:3000/movies in my browser I get the following in my Puma log: 当我在浏览器中访问http://localhost:3000/movies ,我在Puma日志中获得以下内容:

Started GET "/movies" for 127.0.0.1 at 2017-06-17 10:35:00 +0200 Processing by MoviesController#index as HTML Movie Load (1.0ms) SELECT movies .* FROM movies Completed 200 OK in 6ms (Views: 4.0ms | ActiveRecord: 1.0ms) 在2017-06-17 10:35:00开始GET“/ movies”为127.0.0.1 +0200由MoviesController处理#index为HTML电影加载(1.0ms)选择movies 。* FROM movies在6ms完成200 OK(浏览次数: 4.0ms | ActiveRecord:1.0ms)

When I visit http://localhost:4200/ where my Angular application is I get 当我访问http:// localhost:4200 /我的Angular应用程序时,我得到了

Started GET "/movies" for 127.0.0.1 at 2017-06-17 10:37:59 +0200 Processing by MoviesController#index as HTML Movie Load (0.5ms) SELECT movies .* FROM movies Completed 200 OK in 4ms (Views: 2.8ms | ActiveRecord: 0.5ms) 在2017-06-17 10:37:59开始GET“/ movies”为127.0.0.1 +0200由MoviesController处理#index为HTML电影加载(0.5ms)选择movies 。* FROM movies在4ms完成200 OK(浏览次数: 2.8ms | ActiveRecord:0.5ms)

So the Angular application does the request to the API and the API returns the result but that result does not show up in the Angular component. 因此,Angular应用程序向API发出请求,API返回结果,但结果不会显示在Angular组件中。

In Angular we use Observable , which you import from rxjs/Observable , to handle asynchronous code. -在角度我们使用Observable ,你从导入rxjs/Observable ,处理异步代码。

Notice here that when you call this.appService.getMovies() which returns an Observable<Movie[]> , this is essentially an asynchronous operation. 请注意,当您调用this.appService.getMovies()并返回Observable<Movie[]> ,这实际上是一个异步操作。 In the AppComponent you subscribe to it and get the value Asynchrously . AppComponentsubscribe它并获得值Asynchrously

Notice the AppComponent code - 注意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);
        }
  }
}

Hope this helps. 希望这可以帮助。

EXTRA 额外

For more reading on Observable 有关Observable的更多阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM