Peter Boomsma
Peter Boomsma

Reputation: 9808

Get inner object from array

I have a component called MovieSearchComponent. This imports a service MovieSearchService and a model Movie.

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

export class MovieSearchComponent{
  movies: Movie[] = [];

  constructor(private movieSearchService: MovieSearchService){};

  ngOnInit(){
    this.getMovies();
  }

  getMovies(){
    this.movieSearchService.getMovies()
      .subscribe((response)=>{
        this.movies = response;
        console.log(this.movies)
      });
  }
}

The service.

import {Movie} from "../movie";

@Injectable()
export class MovieSearchService{

  private results = {};
  private api = '***7039633f2065942cd8a28d7cadad4';
  private  url = 'https://api.themoviedb.org/3/search/movie?api_key=' + this.api + '&language=en-US&query=Batman&page=1&include_adult=false;';

  constructor(private  http: Http){}

  getMovies(): Observable<Movie[]>{
    return this.http.get(this.url)
      .map(res => res.json())
  }
}

The template:

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

This does show all the titles from the movies that are returned from the service. But I have to select the result array which has all the movie objects in the template, which doesn't look right to me.

When I change the console.log(this.movies) to console.log(this.movies.results) in the MovieSearchComponent I get the error property 'results' does not exist on type Movie[].

This is the movie model:

export class Movie{
  constructor(
    public id: number,
    public title: string,
  ){}
}

So why can't I use console.log(this.movies.results) when I can use it in the template.

Upvotes: 0

Views: 95

Answers (1)

Omri L
Omri L

Reputation: 769

Because results is not defined in Movie Class.

Change your getMovies method to:

 getMovies(): Observable<Movie[]>{
    return this.http.get(this.url)
      .map(res => res.json().results)
  }

Upvotes: 1

Related Questions