【发布时间】:2018-11-25 23:59:53
【问题描述】:
我有一个从外部 api 返回电影数据的 api,我在我的 api 中实现了一个搜索功能,这是我目前所拥有的:
component.ts:
export class MoviesComponent implements OnInit {
movies: any;
searchRes: any;
searchStr: any;
constructor(private router: ActivatedRoute, private http: Http, private location: Location, private moviesService: MoviesService) {
this.movies = [];
}
searchMovies() {
this.moviesService.searchMovies(this.searchStr).then(res => {
this.searchRes = res.results;
});
}
}
service.ts:
export class MoviesService {
searchStr: string;
private apiUrl = 'http://localhost:8000/movies';
constructor(private http: Http, private _jsonp: Jsonp) { }
searchMovies(searchStr: string): Promise<any> {
return this.http.get(this.apiUrl)
.toPromise()
.then(this.handleData)
.catch(this.handleError);
}
private handleData(res: any) {
const body = res.json();
console.log(body); // for development purposes only
return body.result || body || { };
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for development purposes only
return Promise.reject(error.message || error);
}
}
}
compo.html
<form (submit)="searchMovies()">
<input type="text" class="form-control" [(ngModel)]="searchStr" name="searchStr">
<br>
<button class="btn btn-primary btn-lg">Search your Favourite Movies</button>
</form>
<div *ngFor="let movie of searchRes;let i=index" class="col-md-2">
<div *ngIf="i < 18">
<img *ngIf="movie.poster_path" class="thumbnail" src="http://image.tmdb.org/t/p/w500/{{movie.poster_path}}">
<h4>{{movie.title}}</h4>
<p>{{movie.release_date}}</p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
</div>
当我运行该应用程序时一切正常,当我尝试搜索例如复仇者联盟时,它会显示所有电影,而不仅仅是名称为复仇者联盟的电影,我在这里做错了什么?
【问题讨论】:
标签: javascript node.js angular html typescript