Angular - I'm using YouTube player API. I want refresh component with reloading page

701 Views Asked by At

I created a simple application about my work and I am using YouTube player API to play/embed my work videos. All I want is to play random videos every time I visit my portfolio page without reloading. And also I want use play/pause events provided by API, like if video is playing I want to give some tips in below with <p> tag. I'm working with Ionic and I'm using ionViewWillEnter() {} lifecycle to play random videos every time I visit my page.

Here is my code.

portfolio-page.html

<div>
<iframe [src]="randomURL" id="video"></iframe>
<p>{{ tips }}</p>
</div>

portfolio-page.ts

ionViewDidEnter() {
this.tips = "Some tips here"
this.randomURL = "https://www.youtube.com/embed/"my random video URL";

// Play Pause events
window['onYouTubeIframeAPIReady'] = (e) => {
this.YT = window['YT'];
this.player = new window['YT'].Player('player', {
videoId: id,
events: {
'onStateChange': (event) => {
switch (event.data) {
case window['YT'].PlayerState.PLAYING:
this.tip = "Some tips here"
break;

but the problem here is When I visit the page for first time, play pause events work perfectly. if visit the page again play pause events are not working. All i want to do here is to refresh component page(i.e HTML page) only without reloading.

1

There are 1 best solutions below

2
On

You can use :

  1. resolver to generate randomURL and populate component before it will load.

    app-routing.ts

     RouterModule.forRoot([
         {
            path: '/portfolio',
            component: PortfolioPageComponent,
            resolve: { randomURL: PortfolioResolver }
           }
         ])
     ])
    

portfolio-resolver.ts

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs';

export class PortfolioResolver implements Resolve<any> {
  constructor() {}

  resolve(): Observable<any> {
    //generate randomURL
    return randomURL
  }
}

portfolio-page.ts

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

import { ActivatedRoute } from '@angular/router';

@Component({ ... })
export class PortfolioPageComponent implements OnInit {
  data: any;
  randomUrl: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.data = this.route.snapshot.data;
    this.randomUrl = this.data.randomURL;
    // do what you need with new random url
  }
}
  1. simply pass some variable as a flag from parent to child component (or from another place via this.router.navigate(['/portfolio', { reload: true }]);) and receive like this.route.snapshot.paramMap.get('reload'); to notify when it must be reloaded.