ionic 2 app tutorial, a simple YouTube player

Welcome again, today we will build a YouTube player in ionic framework 2 using the YouTube api for search videos and the YouTube iframe api for play videos, so let’s begin.

Ionic framework is a tool for making mobile apps using angular 1 and 2, today we going to be using the version 2 of the framework. for this tutorial you will need to know some typescript,css and html.

Ok so first you need to install ionic on your computer with the  command

npm install -g cordova ionic

Assuming that you already have installed npm and nodejs.

Then create a new project

ionic start ionic-youtube-ng2 blank

This setup for us the ionic blank project, if you want to tested right now you need to get in the directory and type ionic serve and that’s it, the project is running now and we can see it on the browser.

If everything is ok the app is now running on the browser and we can start coding the app, there is not need to reload because the app will refresh automatically.

Ok we will code two services for our app, the first one we call it player.service.ts and we will put it on /src/services folder, this one is for using the iframe api so in order to use this api we need to load it when the app start so in the app.component.ts we need to add these lines on the constructor.

      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

And in the app.module.ts import the required providers.

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { BrowserModule } from '@angular/platform-browser';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { HttpModule } from '@angular/http';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    BrowserModule,
    HttpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
        StatusBar,
        SplashScreen,
        {provide: ErrorHandler, useClass: IonicErrorHandler},
        {provide: Window, useValue: window}
        ]
})
export class AppModule {}

And in the player.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class PlayerService {
  youtube: any = {
    ready: false,
    player: null,
    playerId: null,
    videoId: null,
    videoTitle: null,
    playerHeight: '360',
    playerWidth: '640'
  }

  constructor() {
    this.setupPlayer();
  }

  bindPlayer(elementId): void {
    this.youtube.playerId = elementId;
  };

  createPlayer(): void {
    return new window['YT'].Player(this.youtube.playerId, {
      height: this.youtube.playerHeight,
      width: this.youtube.playerWidth,
      playerVars: {
        rel: 0,
        showinfo: 0
      }
    });
  }

  loadPlayer(): void {
    if (this.youtube.ready && this.youtube.playerId) {
      if (this.youtube.player) {
        this.youtube.player.destroy();
      }
      this.youtube.player = this.createPlayer();
    }
  }

  setupPlayer() {
    //we need to check if the api is loaded
    window['onYouTubeIframeAPIReady'] = () => {
      if (window['YT']) {
        this.youtube.ready = true;
        this.bindPlayer('placeholder');
        this.loadPlayer();
      }
    };
    if (window['YT'] && window['YT'].Player) {
      this.youtube.ready = true;
      this.bindPlayer('placeholder');
      this.loadPlayer();
    }
  }

  launchPlayer(id): void {
    this.youtube.player.loadVideoById(id);
    this.youtube.videoId = id;
    return this.youtube;
  }
}

Ok we have the player service done, to use it we need a video id, so next we code the youtube.service.ts, this one is for search for videos, it can to a lot more but in our app we only going to search and play videos.

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';

@Injectable()

export class YoutubeService {
     googleToken = "your token goes here";
     maxResults = 10;
     url = 'https://www.googleapis.com/youtube/v3/search?part=id,snippet&q=';
     constructor(public http: Http) {}
     public getVideos(query:any){
        return this.http.get(this.url+query+'&type=video&order=viewCount&maxResults='+this.maxResults+'&key='+this.googleToken)
         .map(res => res.json());
     }

}

This service need a google token, you can get one in the google console.

So let’s code view. inside src/pages/ there are our views and in this case we have a home.html, home.scss and a home.ts. home.ts is our main component, in the end this is angular 2 so in the home.ts we are going to call the services that we created.

import { Component } from '@angular/core';

import { NavController,LoadingController } from 'ionic-angular';

import { YoutubeService } from '../../services/youtube.service'
import {PlayerService} from '../../services/player.service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers:[YoutubeService,PlayerService]
})
export class HomePage {
  vPlayer = true;
  videos = {};
  search = {
    params:''
  };

  constructor(public navCtrl: NavController,public player: PlayerService,public youtubeService: YoutubeService,public loadingCtrl:LoadingController) {
    player.setupPlayer();
  }
  findVideos($event){
    let loading = this.loadingCtrl.create({
    });
            loading.present();

    this.youtubeService.getVideos(this.search.params).subscribe(
      videos => {
        this.videos=videos;
        loading.dismiss();
      },
      err=>{
        console.log(err);
      }
    );
  }
  baseUrl:string = 'https://www.youtube.com/embed/';

  playVideo(id){
    this.player.launchPlayer(id)
    this.vPlayer = true; 

  }

}

And in the html

<ion-header>
    <ion-navbar>
        <ion-title>
            Tubeit
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
<div id="player" class="embed-responsive embed-responsive-16by9">
<div id="placeholder" style="width: 100%" class="embed-responsive-item"></div>
<div class="embed-responsive-item" style="width: 100% ; z-index: 90;position: fixed; background-color: black; background: url('images/cover.png'); background-size:cover; " *ngIf="!onPlaying"></div>
</div>
<div id="search-form">
<form (ngSubmit)="findVideos($event)">
            <ion-item>
                <ion-label floating>Search Videos</ion-label>
                <ion-input type="text" [(ngModel)]="search.params" name="search"></ion-input>
                <button type="submit" ion-button icon-only clear item-right>
          <ion-icon name="search"></ion-icon>
        </button>

            </ion-item>
        </form></div>
<div id="results">
<div class="card-background-page">
            <ion-card *ngFor="let video of videos.items">
                <img src="{{video.snippet.thumbnails.high.url}}" />
<div class="card-title">
                    {{video.snippet.title}}</div>
<div class="card-subtitle">
                    {{video.snippet.description}}</div>
<button class="card-btn" (click)="playVideo(video.id.videoId)">
  <ion-icon name="play"></ion-icon>
</button>
            </ion-card></div>
</div>
</ion-content>

As we can see there is two parts in the view, one is the player, and the other are the search forms and the results. with all this we have now a simple youtube client that can run on android or ios.
and the styles…

page-home {}

.card-background-page {
    ion-card {
        position: relative;
        text-align: center;
    }
    .card-title {
        position: absolute;
        top: 36%;
        font-size: 2.0em;
        width: 100%;
        font-weight: bold;
        color: #fff;
        text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
    }
    .card-subtitle {
        font-size: 1.0em;
        position: absolute;
        top: 82%;
        width: 100%;
        color: #fff;
        text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
    }
    .card-btn {
        font-size: 6.0em;
        padding-top: 1%;
        padding-bottom: 1%;
        padding-left: 3%;
        padding-right: 3%;
        position: absolute;
        top: 50%;
        width: 20%;
        left: 40%;
        color: white;
        border-radius: 25%;
        background-color: #333;
    }
    .card-btn:hover {
        background-color: red;
    }
}

For compiling in to an android app we need the android sdk installed in our system, if you have de android sdk to compile the app we type in the terminal this.

ionic platform add android 

Then

ionic build android 

And the .apk is generate in platforms/android/build/outputs/apk/

so that’s all. see ya next time.

UPDATE
the code was updated to work with ionic 3.

Source Code

Advertisements

5 thoughts on “ionic 2 app tutorial, a simple YouTube player

    1. hello, i just update the package.json with the latest ionic apps but i was unable to replicate the error, even on diferents machines with diferents os. what is your setup?
      (updated) the issue is happening with angular 4. so i just update the project to work with ionic 3, and angular 4.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s