如何在Angular2

时间:2017-02-16 14:05:43

标签: json angular object jsonp observable

我正在使用omdbapi.com API为电影数据制作一个简单的搜索引擎。我已设置服务来获取数据和组件以创建视图,但是当我尝试连接到HTML时出现错误:

  

找不到不同的支持对象' [object Object]'类型'对象'。 NgFor仅支持绑定到诸如Arrays之类的Iterables。   错误:无法找到不同的支持对象' [object Object]'类型'对象'。 NgFor仅支持绑定到Iterables,例如Arrays。

电影课

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
    ) {}

}

这是我的组件:

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[]>([]);
        })     
    }
}

这是服务

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[]
            })
    }
}

视图

<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>

如何让视图显示每部电影的电影标题? 提前感谢您的时间。

1 个答案:

答案 0 :(得分:1)

请务必检查网络标签,看看您是否实际接收数据以及数据的外观。

测试这个。显然你首先需要像这样建立你的网址:

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

然后关于响应,它是这样构建的:

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

那么你需要提取什么来获得一个数组:

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

并在您的组件中订阅:

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

然后当您想要显示标题时:

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

请注意上述代码中的SearchTitle。这是区分大小写的,因此您需要使用{{ movie.Title }}和大写T才能显示您的数据。

这应该清楚了! :)