Cara Membangun Aplikasi Ionic 4 Pertama Anda dengan Panggilan API

Jadi Anda baru saja menyadari bahwa Ionic 4 dirilis dan Anda akhirnya ingin memulai pengembangan aplikasi lintas platform? Nah, hari ini adalah harimu! Kami akan membangun aplikasi Ionic 4 pertama Anda dengan Panggilan HTTP ke Open Movie Database!

Apakah Anda benar-benar baru mengenal Ionic atau telah menggunakan versi sebelumnya, kami membahas semua dasar-dasarnya. Kami akan membahas cara menyiapkan aplikasi baru , merutekan , dan bahkan panggilan API untuk menampilkan data asinkron di dalam aplikasi kami.

Jika Anda ingin mempelajari Ionic lebih cepat, Anda juga dapat melihat Akademi Ionic saya yang dibuat untuk pengembang seperti Anda!

Siap ? Pergi !

Menyiapkan Aplikasi Ionic 4 Kami

Jika Anda baru mengenal Ionic Anda perlu memastikan Anda telah menginstal Node Package Manager. Jika Anda pernah bekerja dengan teknologi web lain sebelum peluangnya cukup bagus, Anda sudah mendapatkan semua yang Anda butuhkan.

Jika Anda juga belum pernah menggunakan Ionic sebelumnya, Anda perlu menginstalnya melalui npm. Setelah terinstal, Anda akhirnya siap untuk membuat proyek Ionic 4 Anda!

Untuk menyiapkan proyek kosong Anda dapat menggunakan Ionic CLI sehingga kami berakhir dengan proyek Ionic 4 baru dengan dukungan Angular ( Anda juga dapat menggunakan React atau Vue, dukungan yang lebih baik akan datang akhir tahun ini ).

Setelah proyek dibuat, kami cd ke dalam folder. Kami menggunakan CLI, yang menggunakan CLI Angular di bawah tenda, untuk membuat halaman baru untuk aplikasi kami yang ingin kami tampilkan.

# Install Ionic if you haven't before npm install -g ionic # Create a blank new Ionic 4 app with Angular support ionic start movieApp blank --type=angular cd movieApp # Use the CLI to generate some pages and a service ionic g page pages/movies ionic g page pages/movieDetails ionic g service services/movie

Sekarang Anda dapat langsung membuka aplikasi Anda dengan menjalankan perintah berikut di dalam proyek Anda:

ionic serve

Ini akan membuka browser dengan pratinjau aplikasi Anda yang akan dimuat ulang secara otomatis setelah Anda mengubah apa pun di dalam proyek Anda.

Berbicara tentang proyek, kami mendapat banyak file dan folder di sini, mari kita lihat apa artinya semua ini. Kami akan fokus pada folder src dari aplikasi kami karena kami tidak perlu mengkhawatirkan sisanya untuk saat ini.

Aplikasi

Ini adalah folder tempat kita akan membuat semua perubahan kode yang mengikuti nanti dalam tutorial ini. Itu sudah berisi folder rumah yang pada dasarnya adalah halaman seperti yang kita buat sebelumnya. Saya ingin memiliki semua halaman di folder halaman mereka sendiri sehingga Anda dapat menghapus folder home juga untuk saat ini.

The halaman folder berisi aktual views / halaman aplikasi kami, yang berarti elemen kita akan melihat di layar. Saat ini kami sudah mendapatkan 2 halaman di sini, dan setiap halaman yang Anda buat dengan CLI dilengkapi dengan 4 file:

  • * .module.ts: Modul Angular untuk halaman. Setiap halaman pada dasarnya adalah modul mereka sendiri (terkait dengan arsitektur Angular) dengan impor dan gaya
  • * .page.html: Markup HTML untuk halaman
  • * .page.scss: Gaya untuk halaman tertentu (lebih lanjut tentang gaya global nanti)
  • * .page.spec.ts: File pengujian yang ditambahkan secara otomatis untuk halaman Anda. Baik jika Anda ingin menyiapkan pengujian unit otomatis
  • * .page.ts: Pengontrol untuk halaman yang berisi kode Javascript yang mengelola fungsionalitas tersebut

The pelayanan folder berisi layanan kami sebelumnya dibuat - ini adalah tentang penataan aplikasi Anda sesuai dengan praktik terbaik dan memisahkan kekhawatiran antara tampilan dan data aktual aplikasi Anda. Layanan akan menangani penanganan panggilan API dan hanya mengembalikan data ke tampilan kami nanti!

Aktiva

Folder ini berisi semua gambar, font, atau aset apa pun yang Anda butuhkan untuk aplikasi Anda nanti.

Lingkungan

Dari waktu ke waktu, project Anda mungkin memiliki lingkungan pengembangan, pementasan, dan produksi dengan server berbeda yang ditargetkan aplikasi Anda. Folder lingkungan membantu mengatur informasi untuk lingkungan yang berbeda. Kita nantinya dapat membangun aplikasi Ionic kita dengan flag baris perintah dan secara otomatis mengambil nilai yang benar. Sangat berguna!

Tema

Folder ini hanya berisi variabel.scss yang berisi informasi warna standar dari Ionic. Kami selalu dapat mengubah file ini dan bahkan menggunakan alat seperti Ionic Color Generator untuk membuat versi rasa kami sendiri dari file ini!

Di luar folder kami juga memiliki global.scss. Di sini kita dapat menulis beberapa SCSS yang akan diterapkan secara global ke aplikasi kita. Kami juga dapat mendefinisikannya hanya untuk satu halaman di file gaya mereka sendiri.

File Lainnya

File lain yang paling relevan mungkin adalah index.html karena sama seperti situs web lainnya, file ini menandai titik masuk ke aplikasi kita! Untuk saat ini, meskipun kita tidak perlu mengubah apa pun di sini, jadi sekarang mari kita mulai masuk ke kode yang sebenarnya.

Perutean Prasyarat & Panggilan HTTP

Dengan Ionic 4 kita beralih dari konsep perutean berpemilik ke Router Sudut standar. Markup mungkin terlihat sedikit lebih sulit pada awalnya, tetapi sebenarnya sangat masuk akal.

Untuk semua koneksi di dalam aplikasi Anda, Anda menyiapkan informasi perutean di muka - sama seperti Anda menjelajahi situs web!

Di aplikasi kami, kami membutuhkan 2 rute:

  • / film - Buka halaman pertama kami yang seharusnya menampilkan daftar film
  • / movies /: id - Kami ingin menampilkan detail untuk satu film, jadi kami menambahkan param : id ke rute yang dapat kami selesaikan secara dinamis

Kita juga perlu menghubungkan halaman yang sesuai ( lebih spesifik : modul halaman) ke rute sehingga Angular tahu bagaimana menyelesaikan rute tertentu. Kami menyediakan informasi ini menggunakan loadChildren yang sebenarnya hanya mendapatkan string ke jalur modul .

Ini berarti kami tidak benar-benar mengimpor modul lain di sini, oleh karena itu, halaman menggunakan pemuatan lambat. Itu berarti mereka hanya akan dimuat setelah kita menavigasi ke sana!

Untuk menyiapkan informasi perutean kami, buka app / app-routing.module.ts kami dan ubah ke:

import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = [ { path: '', redirectTo: 'movies', pathMatch: 'full' }, { path: 'movies', loadChildren: './pages/movies/movies.module#MoviesPageModule' }, { path: 'movies/:id', loadChildren: './pages/movie-details/movie-details.module#MovieDetailsPageModule' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

By making this change we have also disconnected the home page which was initially in the project (and which you might have deleted already at this point).

Now the app will load our movies page as the first page, great! You should also notice this change in your running ionic serve instance already.

Tip: If you want to get a better feeling for how your app will look on a real device you can also run ionic lab instead of serve but you have to install the package upfront:

# Install the Lab Package npm i @ionic/lab # Run your app with device preview and platform styles ionic lab

This package was previously bundled with every new app but needs to be installed for Ionic 4 now.

/Tip End

We also need to apply another change to our app as we want to make HTTP calls. Therefore we need to import another Angular module for making those requests.

The way of doing this is the same as with Ionic 3. We just need to add the HttpClientModule to our main module file and add it to the array of imports like this inside our app/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'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule], providers: [ StatusBar, SplashScreen, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule {}

Before we dive into more Ionic 4 code we first have to set up the service that powers our app and handles all the HTTP requests that we later want to call.

Making HTTP Requests

A service is the same as in previous versions a provider and can be injected into our controller in order to call its functions.

In order to use the Open Movie Database you need to request an API key and insert it into our service — the process is free so go ahead right now.

With the API we can now search for strings and get results in form of movies, episodes or even games. Also, we can get detailed information for one specific object of those results so a perfect use case for our first Ionic 4 app!

Our service only needs 2 functions:

  • searchData(): This function searches for results to a specific title and search type – an enum we defined upfront to represent the types that we can pass to the API using TypeScript!
  • getDetails(): This function returns the detailed information for one specific element, will be used on our details page

Both functions will return an Observable which is like a Promise on steroids. No serious, it’s like a stream of events that we can subscribe to. Explaining this concept would take another post. For now, let’s use it and keep in mind that both of our functions are async — they will return the API data not immediately.

Now go ahead and change your services/movie.service.ts to:

import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; // Typescript custom enum for search types (optional) export enum SearchType { all = '', movie = 'movie', series = 'series', episode = 'episode' } @Injectable({ providedIn: 'root' }) export class MovieService { url = '//www.omdbapi.com/'; apiKey = ''; // <-- Enter your own key here! /** * Constructor of the Service with Dependency Injection * @param http The standard Angular HttpClient to make requests */ constructor(private http: HttpClient) { } /** * Get data from the OmdbApi * map the result to return only the results that we need * * @param {string} title Search Term * @param {SearchType} type movie, series, episode or empty * @returns Observable with the search results */ searchData(title: string, type: SearchType): Observable { return this.http.get(`${this.url}?s=${encodeURI(title)}&type=${type}&apikey=${this.apiKey}`).pipe( map(results => results['Search']) ); } /** * Get the detailed information for an ID using the "i" parameter * * @param {string} id imdbID to retrieve information * @returns Observable with detailed information */ getDetails(id) { return this.http.get(`${this.url}?i=${id}&plot=full&apikey=${this.apiKey}`); } }

I’ve also added some documentation to the functions — with a tool like Compodoc you could now create nice documentation!

Alright, now we are finally ready for some more Ionic 4 code!

Searching for Movies

We start our apps functionality with the things that happen in the background and then build the view on top of it.

So right now we need to implement the logic to submit a search term and type to our service and receive the results. Therefore, we inject the service through our constructor so it’s available to the class.

In another function that we call searchChanged() we will now simply call the according function of our service and set the result to a local variable b>results. Our view will later handle the data that comes from the API and display it using this variable.

We also keep 2 more variables for the searchTerm and type inside our class that we pass to the service. We will connect with them from the view as well so we can change them.

Now go ahead with the code for your controller inside the pages/movies/movies.page.ts:

import { MovieService, SearchType } from './../../services/movie.service'; import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; @Component({ selector: 'app-movies', templateUrl: './movies.page.html', styleUrls: ['./movies.page.scss'], }) export class MoviesPage implements OnInit { results: Observable; searchTerm: string = ''; type: SearchType = SearchType.all; /** * Constructor of our first page * @param movieService The movie Service to get data */ constructor(private movieService: MovieService) { } ngOnInit() { } searchChanged() { // Call our service function which returns an Observable this.results = this.movieService.searchData(this.searchTerm, this.type); } }

Now the view which looks a lot like Ionic 3 code, just a few of the elements changed their names and properties. For everyone new to Ionic in general: Welcome to your first Ionic components!

A page can be separated into 3 areas: Header, content, footer. In our case, we don’t want a footer so we only define the header area with a title and the content with our actual elements for the search.

The first element that affects the search is the ion-searchbar which is a simple input you have seen in many apps before to search for a term.

We always want to call our search functionality when the type or searchTerm changes. We can do this by catching the (ionChange) event of some of our elements.

Below we got a select drop down with options and the according value for the different types that we could pass back to the API.

You should have also noticed the [(ngModel)] syntax through which both elements are connected to our controller properties. If one side changes, the other will automatically get the new value as well (also known as 2-way data binding).

So we got the search in place and now add another list with elements below our previous components.

For the list, we use an iteration over our results variable. Because this variable is an Observable (remember the implementation in our service) we need to add an Angular Pipe “| async” to it. The view subscribes to the Observable and handles the changes accordingly.

We also add the routing directly to this element by using [routerLink]. We construct the path that we want to open when we click on the element. We use the imdbID property of the item so we can resolve the information on our details page later.

Besides that, we create the markup for one item using the Poster which is an image, the title, year and finally also a cool icon at the and based on the type of the item. Yes, those cool icons are already bundled with your app and are called Ionicons!

With all of that in mind change your pages/movies/movies.page.html to:

  My Movie Search      Select Searchtype  All Movie Series Episode      

{{ item.Title }}

{{ item.Year }}

By now you should be able to search for a specific term inside your app and get a list of results — that’s already a big win!

If you are coming form Ionic 3 you might have also noted another new property called slot so here’s some info on that:

Ionic 4 components are built using Stencil (yeah, they actually created that tool as well!) so they are standard web components — you could import them basically everywhere on the web! These components also use the Shadow DOM API and are basically living outside of the scope of your regular DOM elements.

That means also standard styling will sometimes not affect these components like it was possible in previous versions!

In order to get information into these components, we can inject certain parts of HTML into their slots that are defined on these elements. You can see how their implementation looks like on the example of the ion-item we used here.

Presenting Detailed Information

Ok enough of background information, let’s put some more work into the details page of our app. We have implemented a route and we also created a button that passed an ID with that route so the details page will be open, but we need to get access to the ID!

With previous Ionic versions we could easily pass whole objects to new pages, this is now not a best practice anymore. Instead, we pass only small chunks of information (like an ID) with the URL. Otherwise, you would end up with a huge JSON stringified term inside the URL. This isn’t really something we want to have.

To get access to this ID field (that we already defined inside our routing in the beginning) we can use the ActivatedRoute and its properties.

So after we extract the ID from the params we can make another call to our service (that we injected through the constructor again) and get the detailed information for whatever ID we got.

Nothing really new so let’s add the following code to our pages/movie-details/movie-details.page.ts:

import { MovieService } from './../../services/movie.service'; import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-movie-details', templateUrl: './movie-details.page.html', styleUrls: ['./movie-details.page.scss'], }) export class MovieDetailsPage implements OnInit { information = null; /** * Constructor of our details page * @param activatedRoute Information about the route we are on * @param movieService The movie Service to get data */ constructor(private activatedRoute: ActivatedRoute, private movieService: MovieService) { } ngOnInit() { // Get the ID that was passed with the URL let id = this.activatedRoute.snapshot.paramMap.get('id'); // Get the information from the API this.movieService.getDetails(id).subscribe(result => { this.information = result; }); } openWebsite() { window.open(this.information.Website, '_blank'); } }

We also added another function to open a website using the window object and the information from the data of the API that we stored in the local information variable.

Now we just need to create a view based on the JSON information of the API. It always helps to log() out the info you got so you see keys that you can use to display some values.

In our case, we use the Ionic card component and add the image and some items with information and more icons (did I say I really like the Ionicons?).

We also added a button below that card that will be displayed if the result information contains the website key. We just have to add our function to the (click) event of the button in order to hook everything up!

On another note, we also have to add an ion-back-button to the header of that page in order to get a nice little back arrow to our previous movie list page. This was automatically done in v3 but needs to implemented manually as of v4!

Now finish your details view by changing your pages/movie-details/movie-details.page.html to:

     {{ information?.Genre }}       {{ information.Title }}   {{ information.Year }}     {{ information.Plot }}   {{ information.imdbRating }}    {{ information.Director }}    {{ information.Actors }}    Open Website    

If you now take a look at your browser you might notice that the image looks waaaay to big as its taking all the space available. Let’s change this through some good old CSS so open your pages/movie-details/movie-details.page.scss and insert:

.info-img { max-height: 30vh; object-fit: contain; padding: 10px; }

Now our results look a lot more appealing.

We can search, select a movie type, dive into a search result and have a fully functional Ionic 4 app with HTTP calls finished!

Conclusion

While it was a straight forward experience to build our first Ionic 4 app there are so many things we haven’t talked enough about.

UI patterns like Tabs and side menu, CSS variables, responsive layout and PWA to just name a few on the side of Ionic and Angular.

And we haven’t even touched the Cordova side of things to actually build this app into a real native mobile app!

If you want to learn how to develop Ionic 4 apps as fast as possible and get them to the iOS & Android app stores quickly you can join the Ionic Academy today and enjoy expert screencasts, a library of quick wins and a community to support you on your journey!

And of course, I (Simon) am also present inside to answer all your questions all the time

You can also find a video version of this guide below!

Originally published at ionicacademy.com on January 24, 2019.