2016-09-06 8 views
0

私のJSONリクエストは、次の値を返します。JSON配列のPromiseの助けを借りてパラメータでオブジェクトを見つける方法は?

{"page": 1, 
    "results": [ 
    { 
     "poster_path": "/9O7gLzmreU0nGkIB6K3BsJbzvNv.jpg", 
     "adult": false, 
     "overview": "Framed in the 1940s for the double murder of his wife and her lover, upstanding banker Andy Dufresne begins a new life at the Shawshank prison, where he puts his accounting skills to work for an amoral warden. During his long stretch in prison, Dufresne comes to be admired by the other inmates -- including an older prisoner named Red -- for his integrity and unquenchable sense of hope.", 
     "release_date": "1994-09-10", 
     "genre_ids": [ 
     18, 
     80 
     ], 
     "id": 278, 
     "original_title": "The Shawshank Redemption", 
     "original_language": "en", 
     "title": "The Shawshank Redemption", 
     "backdrop_path": "/xBKGJQsAIeweesB79KC89FpBrVr.jpg", 
     "popularity": 5.446135, 
     "vote_count": 5250, 
     "video": false, 
     "vote_average": 8.32 
    }, 
    { 
     "poster_path": "/lIv1QinFqz4dlp5U4lQ6HaiskOZ.jpg", 
     "adult": false, 
     "overview": "Under the direction of a ruthless instructor, a talented young drummer begins to pursue perfection at any cost, even his humanity.", 
     "release_date": "2014-10-10", 
     "genre_ids": [ 
     18, 
     10402 
     ], 
     "id": 244786, 
     "original_title": "Whiplash", 
     "original_language": "en", 
     "title": "Whiplash", 
     "backdrop_path": "/6bbZ6XyvgfjhQwbplnUh1LSj1ky.jpg", 
     "popularity": 9.001948, 
     "vote_count": 2072, 
     "video": false, 
     "vote_average": 8.28 
    }, 

私はサービスの助けを借りて、そのIDの後に特定のオブジェクトを検索してみてください。

@Injectable() 
export class MovieService { 

    constructor(private http:Http) { } 

    getMovies(): Promise<Movie[]>{ 

     return this.http.get('http://api.themoviedb.org/3/movie/top_rated?api_key=API-KEY') 
      .toPromise() 
      .then((res:Response) => res.json()['results']) 

    } 
    getMovie(id: number): Promise<Movie> { 
     return this.getMovies() 
      .then(movies => movies.find(movie => movie.id == id)); 

    } 
} 

getMovie上記ザ・()メソッドが例外を返します。 :Uncaught(約束で)、idは未定義のエラーです。 リクエストされたオブジェクトを検索するにはどうすればよいですか?

+0

あなたのコードは、それはあなたがしなければ何を印刷しない、私には罰金です。 movies.find(movie => movie.id == id)} '? –

+0

@NitzanTomer選択したIDをコンソールに記録します。うーん、興味深い。私は私の質問を更新します。 – GaborH

+0

さて、 'id'はそこにあり、' undefined'であるべきではありません。これは実行している正確なコードですか、変更したバージョンを投稿しましたか?あなたはそのエラーがその行から来ていると確信していますか? –

答えて

0

に役立ちます。私は* ngIf = "映画" を追加するのを忘れて、テンプレートで

ngOnInit(): void { 
     this.route.params.forEach((params: Params) => { 
      let id = +params['id']; 
      this.movieService.getMovie(id) 
       .then(movie => this.movie = movie); 

     }); 
    } 

:私は、以下の方法をgetMovie(ID)関数を呼び出しました。追加した後、すべてが期待通りに機能しました。 `映画=> {はconsole.log( "IDを探している:" + ID)

@Component({ 

    selector: 'topmovies', 
    template: ` 
    <div *ngIf="movie">// I forgot to add this line 
    <h2>{{movie.id}}</h2> 
    <h2>{{movie.original_title}} </h2> 
    </div> 

    ` 
}) 
0

私はあなたの問題を解決する大声を作成しました。

plunker

非常に観測代わりの約束を使用することが推奨されていることに注意してください。

これはサービスの2つの方法です。

getMovies() : Observable<any>{ 
    return this.http.get('./src/data.json') 
} 
getMovieById(id: number): Observable<any> { 
    return this.getMovies().map(res =>{ 

     let response = res.json()['results']; 

     return response.find(item => item.id === id) 
    }) 
} 

、ここでは、私がここで観測(オンライン情報源の多く)に詳細には触れませんcompontent

export class App { 
    constructor(private movieService:MovieService) { 
    this.movieService.getMovieById(278).subscribe(res => console.log(res)) 
    } 
} 

です。あなたがそれらに精通していない場合には、それらを約束と出来事のミックスと考えることが大いに役立ちます。

イベントが発生するたびに、オブザーバブルはイベントをサブスクライブしたすべてのイベントに送信します。サブスクライブはforEachと簡単に見なすことができます。

よう

this.movieService.getMovieById(278).subscribe(res => console.log(res)) 

this.movieService.getMovieById(278).forEach(res => console.log(res)) 

として解釈することができ、毎回観測が何かを放出する、放出された値は、のforeach関数に渡されます。

希望これは私が私のTopmoviesDetailコンポーネントに間違いを見つけた

乾杯

+0

私のコードで間違いを見つけました。上記の詳細を見ることができます。私はObservableへの私の約束を変更します。あなたのご意見ありがとうございます、私はそれを感謝します。 – GaborH

+0

あなたの歓迎:)すべてが解決された場合は、オフになっているかどうかを確認してください。乾杯 –

関連する問題