嘿伙计们我正在尝试使用Angular2中的Observables进行实时搜索,以从OMDB API中检索电影信息。我可以看到它在Chrome网络标签中有效,但我没有在UI中获得结果。
@Component({
selector: 'movie-card',
templateUrl: './card.component.html'
})
export class Component implements OnInit{
movies: Observable<Array<Movie>>;
search = new FormControl;
constructor(private service: MovieService) {}
ngOnInit(){
this.movies = this.search.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(search => this.service.get(search))
}
}
MovieService
@Injectable()
export class MovieService {
constructor (private http: Http) { }
get(path: string){
return this.http
.get('www.omdbapi.com/?s=' + path)
.map((res) => res.json())
}
}
在我的HTML组件中,我有一个输入,然后是UI来显示结果。
<input [formControl]="search">
<div *ngFor="let movie of movies | async">
<h1>{{movie.title}}</h1>
当我输入时,我会在网络标签中看到结果,如下所示:
但它没有显示在UI中。有人可以帮忙吗?感谢
答案 0 :(得分:1)
您正在使用的服务返回一个JSON对象 - 而不是一个数组。例如,http://www.omdbapi.com/?s=jason%20bourne
将返回如下内容:
{
"Search": [
{
"Title": "Jason Bourne",
"Year": "2016",
"imdbID": "tt4196776",
"Type": "movie",
"Poster": "https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTU1ODg2OTU1MV5BMl5BanBnXkFtZTgwMzA5OTg2ODE@._V1_SX300.jpg"
},
...
],
"totalResults": "16",
"Response": "True"
}
因此,如果您的服务应该返回一组电影,它应该返回结果的Search
属性:
@Injectable()
export class MovieService {
constructor (private http: Http) { }
get(path: string){
return this.http
.get('www.omdbapi.com/?s=' + path)
.map((res) => res.json().Search || [])
}
}
答案 1 :(得分:0)
这种方式对我有用:在角度6中
服务文件:
import { Injectable } from '@angular/core';
import 'rxjs/RX';
import 'rxjs/add/operator/map';
import {Http, Response} from '@angular/http';
@Injectable()
export class omdbService {
searchMovieByTitle(title: String) {
const url = 'http://www.omdbapi.com/?s=' + title + '&apikey=da53126b';
return this.http.get(url).map( (response: Response ) => {
return response.json(); } ); }
constructor (private http: Http) { }
}
HTML文件:
<label>movietitle</label>
<input #input class="form-control" />
<button mdbBtn type="button" color="info" outline="true" mdbWavesEffect
(click)="searchMovie(input.value)" >
Search
</button>
<ul class="list-group">
<li class="list-group-item" *ngFor =" let movie of result.Search" >
{{movie.Title}} {{movie.imdbID}}
</li>
</ul>
Ts文件:
import { omdbService } from './../service/omdb.service';
import { Component } from '@angular/core';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent {
title = '';
result: Object = null;
searchMovie(title: String) {
this.OmdbService.searchMovieByTitle(title).subscribe( (result) => {
this.result = result; console.log(result);
}); }
constructor(private OmdbService: omdbService) { }
}