简体   繁体   English

在Angular2中从外部源获取JSON后如何显示结果

[英]How to display results after fetching JSON from external source in Angular2

I'm making a simple search engine for movie data using omdbapi.com API. 我正在使用omdbapi.com API为电影数据制作一个简单的搜索引擎。 I've set up the service to fetch the data and the components to create the view but when I try to connect to the HTML i get an error: 我已经设置了服务来获取数据和组件以创建视图,但是当我尝试连接到HTML时出现错误:

Cannot find a differ supporting object '[object Object]' of type 'object'. 找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor only supports binding to Iterables such as Arrays. NgFor仅支持绑定到Iterables,例如数组。 Error: Cannot find a differ supporting object '[object Object]' of type 'object'. 错误:找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor only supports binding to Iterables such as Arrays. NgFor仅支持绑定到Iterables,例如数组。

Movie class 电影课

export class Movie {
    constructor(
        Title: string,
        Year: string,
        Rated: string,
        Released: string,
        Runtime: string,
        Genre: string,
        Director: string,
        Writer: string,
        Actors: string,
        Plot: string,
        Language: string,
        Country: string,
        Awards: string,
        Poster: string,
        Metascore: string,
        imdbRating: string,
        imdbVotes: string,
        imdbID: string,
        Type: string,
        Response: string
    ) {}

}

Here is my component: 这是我的组件:

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

//observable class extensions
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map';
//observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

import { MovieSearchService } from './movie-search.service';
import { Movie } from './movie';

@Component({
    selector: 'movie-search',
    templateUrl: './movie-search.component.html',
    styleUrls: ['./movie-search.component.css'],
    providers: [MovieSearchService]
})

export class MovieSearchComponent implements OnInit {
    movies: Observable<Movie[]>;
    private searchTerms = new Subject<string>();

    constructor(
        private movieSearchService: MovieSearchService,
        private http: Http
    ) {}

    search(term:string) {
        return this.searchTerms.next(term);
    }

    ngOnInit(): void {
      this.movies = this.searchTerms
        .debounceTime(300) // wait 300ms after each keystroke before considering the term
        .distinctUntilChanged() // ignore if next search term is same as previous
        .switchMap(term => term // switch to new observable each time the term changes
        // return the http search observable
        ? this.movieSearchService.search(term)
            // or the observable of empty heroes if there was no search term
        : Observable.of<Movie[]>([])
        )
        .catch(error => {
            console.log("--------- Error -------");
            console.log( error );

            return Observable.of<Movie[]>([]);
        })     
    }
}

This is the service 这是服务

import { Injectable } from '@angular/core';
import { Http, Jsonp } from '@angular/http';

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

import { Movie } from './movie';

@Injectable()
export class MovieSearchService {
    constructor(
        private http: Http,
        private jsonp: Jsonp
    ) {}

    search(term: string): Observable<Movie[]> {
        return this.http
            .get(`http://www.omdbapi.com/?s=${term}`)
            .map(response => {
                return response.json().each() as Movie[]
            })
    }
}

And the view 和看法

<div class="col-xs-12">
   <input #searchBox id="search-box" />
   <button (click)="search(searchBox.value)">Search</button>
</div>

<ul *ngIf="movies">
    <li *ngFor="let movie of movies">
        {{ movie.title }}
    </li>
</ul>

How may I make the view show the movie title for each movie? 如何使视图显示每部电影的电影标题? Thanks in advance for your time. 在此先感谢您的时间。

Always check the network tab to see if you are actually receiving data and how that data looks like. 请始终检查“网络”标签,以查看您是否实际在接收数据以及该数据的外观。

Testing this. 测试一下。 Apparently you first of all need to build your url like this: 显然,您首先需要像这样构建您的网址:

return this.http.get('http://www.omdbapi.com/?s='+term)

Then as to the response, it's built like this: 然后,对于响应,它是这样构建的:

{"Search":[{"Title":"24","Year":"2001–2010","imdbID"....

So what you need to extract to get an array: 因此,您需要提取以获得数组:

.map(response => {response.json().Search})

and subscribe in your component: 并订阅您的组件:

this.movieSearchService.search(term)
  .subscribe(d => this.movies = d)

and then when you want to display your title: 然后当您想显示标题时:

<ul *ngIf="movies">
    <li *ngFor="let movie of movies">
        {{ movie.Title }}
    </li>
</ul>

Notice the Search and Title in the above codes. 请注意上述代码中的SearchTitle This is case sensitive, so you need to eg use {{ movie.Title }} with a capital T to be able to display your data. 这是区分大小写的,因此您需要例如将{{ movie.Title }}与大写T配合使用才能显示数据。

This should clear things up! 这应该清除一切! :) :)

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

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