Reputation: 1081
I have api which return movies data from external api, I have implemented a search function in my api , here is what i have so far:
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>
when I run the app everything works fine and when I trie to search eg Avengers, it displays all movies not just movies which goea by the name avengers, what am I doing wrong here?
Upvotes: 0
Views: 763
Reputation: 222542
The problem above is even though you are passing searchStr
as a parameter to the method, you are not actually passing to the api
,
searchMovies(searchStr: string): Promise<any> {
return this.http.get(this.apiUrl) //pass **`searchStr`** here
.toPromise()
.then(this.handleData)
.catch(this.handleError);
Upvotes: 1