从数组

时间:2017-06-25 18:03:15

标签: javascript angular

我有一个名为MovieSearchComponent的组件。这会导入服务MovieSearchService和模型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)
      });
  }
}

服务。

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

模板:

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

这会显示从服务返回的电影中的所有标题。但是我必须选择包含模板中所有电影对象的结果数组,这对我来说并不合适。

当我在console.log(this.movies)中将console.log(this.movies.results)更改为MovieSearchComponent时,我收到错误property 'results' does not exist on type Movie[].

这是电影模型:

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

为什么我可以在模板中使用console.log(this.movies.results)时使用-S

1 个答案:

答案 0 :(得分:1)

因为未在影视类中定义结果。

将getMovies方法更改为:

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