[Fixed] creating a link to youtube channel on angular

Issue

I am trying to link my youtube channel with my angular app.

I have tried the following and am getting the error:

Error: Uncaught (in promise): TypeError: You provided ‘undefined’ where a stream was expected.

my page.ts file is:

import { Component, OnInit } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { YoutubeService } from './youtube.service'
import { takeUntil } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Component({
selector: 'app-coachingtips',
templateUrl: './coachingtips.page.html',
styleUrls: ['./coachingtips.page.scss'],
})
export class CoachingtipsPage implements OnInit {
videos: any[];
unsubscribe$: Observable<any>;

constructor(private youTubeService: YoutubeService) { }

ngOnInit() {
this.videos = [];
this.youTubeService
.getVideosForChanel('MY-CHANNEL-ID', 3)
.pipe(takeUntil(this.unsubscribe$))
.subscribe(lista => {
for (let element of lista["items"]) {
this.videos.push(element)
}
});
}}

my youtube.service.ts file is:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class YoutubeService {

apiKey : string = 'MY-API-KEY';

constructor(public http: HttpClient) { }

getVideosForChanel(channel, maxResults): Observable<Object> {
let url = 'https://www.googleapis.com/youtube/v3/search?key=' + this.apiKey + '&channelId='   
+ channel + '&order=date&part=snippet &type=video,id&maxResults=' + maxResults
return this.http.get(url)
  .pipe(map((res) => {
    return res;
  }))
}}

if there is anything you can recommend I would hugely grateful? many thanks

console.log(this.videos)

enter image description here

Solution

You don’t need the takeUntil(this.unsubscribe$), http subscriptions are automatically removed when component is destroyed and this is what cause you trouble.

import { Component } from '@angular/core';
import { AppService } from './app.service';

@Component({
selector: 'app-coachingtips',
templateUrl: './coachingtips.page.html',
styleUrls: ['./coachingtips.page.scss'],
})
export class CoachingtipsPage implements OnInit {
  videos: any[];
  constructor(private youTubeService: YoutubeService) {
  }
  ngOnInit() {
    this.videos = [];
    this.youTubeService.getVideosForChanel('MY-CHANNEL-ID', 3)
    .subscribe(lista => {
      for (let element of lista["items"]) {
        this.videos.push(element)
        }
    });
  }
}

It should work better, now you should have a 400 http error: API key not valid. Please pass a valid API key. So with valid api key it should be ok.

I manage to reproduce your problem here: https://stackblitz.com/edit/angular-s4xrvg?file=src%2Fapp%2Fapp.component.ts

Leave a Reply

(*) Required, Your email will not be published