2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ionic + Angular】TMDb APIで映画の検索を実装する

Posted at

#出来上がりはこんな感じ

#TMDb APIの準備
【Ionic + Angular】TMDb APIで映画の一覧を取得して表示する
一応この記事の続きってことで、APIどうすればいいかわからない人はまず上記の記事を確認してね:wink:

#HttpClientJsonpModuleをimport
jsonpと言うメソッドを使うために、HttpClientJsonpModuleapp.module.tsにimportする

app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

// HttpClientJsonpModuleを追加
import { HttpClientJsonpModule, HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    HttpClientModule,
   // HttpClientJsonpModuleを追加
    HttpClientJsonpModule,
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

#API情報を扱うserviceを作る

ionic g service service/api

これでserviceフォルダの中にapi.service.tsが作成されたかと。

api.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  apiKey = '***';
  // 最後に &language=ja をつけると日本語に
  getNowPlayingURL = `https://api.themoviedb.org/3/movie/now_playing?api_key=${this.apiKey}`;

  constructor() { }
}

コメントにある通り&language=jaを最後につけると、API情報が日本語で取得できます(日本語の情報がある場合のみ)
https://developers.themoviedb.org/3/getting-started/languages

#検索のページを作る
search用のページを作る

ionic g page search

ここで登場するのがjsonp
このメソッドが何をしているのかは知らんけど、参考にしたサンプルが使ってたから使いました:smiley:

search.page.ts
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../service/api.service';

@Component({
  selector: 'app-first-register',
  templateUrl: './first-register.page.html',
  styleUrls: ['./first-register.page.scss'],
})
export class SearchPage implements OnInit {
  query: string;
  movies: any[];

  constructor(
    private apiService: ApiService,
    private http: HttpClient,
  ) { }

  ngOnInit() {
  }

  search() {
    console.log(this.query);
    if (this.query) {
      const searchURL = `https://api.themoviedb.org/3/search/movie?api_key=${this.apiService.apiKey}&query=${this.query}`;
      return this.http.jsonp(searchURL, 'callback').subscribe((data: any) => {
        this.movies = data.results;
      });
    } else {
      console.log('もうあるよ!');
    }
  }

}
search.page.html
<ion-header>
  <ion-toolbar color="primary">
    <ion-buttons slot="start">
      <ion-back-button defaultHref="/home"></ion-back-button>
    </ion-buttons>
    <ion-title>検索してみよか</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-grid>
    <ion-row>
      <ion-searchbar [(ngModel)]="query"></ion-searchbar>
    </ion-row>
    <ion-row>
      <ion-col>
        <ion-button class="bold" expand="block" fill="solid" color="primary" (click)="search()">
          <ion-icon name="search" slot="start"></ion-icon>
          検索
        </ion-button>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col *ngIf="movies">
        <ion-card *ngFor="let movie of movies">
          <div class="ion-text-center">
            <img src="https://image.tmdb.org/t/p/w300_and_h450_bestv2/{{movie.poster_path}}" />
          </div>
          <ion-card-header>
            <ion-card-subtitle>{{ movie.release_date }}</ion-card-subtitle>
            <ion-card-title>{{ movie.title }}</ion-card-title>
          </ion-card-header>
        
          <ion-card-content>
            {{ movie.overview }}
          </ion-card-content>
        </ion-card>
      </ion-col>
    </ion-row>
  </ion-grid>

</ion-content>

#参考にしたリンク
https://mrkmyki.com/逆引きangular/angularでjsonpを使いデータを受信する

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?