Roy
Roy

Reputation: 1

Using subscribe function getting cannot read undefined

I am trying to get information from another component that sends HTTP request with youtube API and I get this problem:

Cannot read property 'subscribe' of undefined
at SafeSubscriber._next (profile.page.ts:20)

this the component code, from here I trying to get the information from the service:

  constructor(private db:FirebaseService,private afauth:AuthService) { 
  this.db.getDataObj("/Profile/" + this.uid).subscribe(res =>{
     this.profileInfo= res;
     this.afauth.getYoutubeData(res.channel).subscribe(data =>{
       console.log(data);
  })
})}

this the code of the function of the service that send the http request:

 getYoutubeData(ch):any{
  let m="https://www.googleapis.com/youtube/v3/channels? 
  part=snippet%2CcontentDetails%2Cstatistics&id=" + ch + "&key=" + api ;
  this.http.get(m).subscribe(data =>
  { 
   this.youtubeObj=data.items["0"].statistics;
   return this.youtubeObj;
 })

}

Upvotes: 0

Views: 168

Answers (3)

Vadim
Vadim

Reputation: 3439

You need to correct your getYoutubeData method in the service by removing subscription and returning this.http.get. To get data.items["0"].statistics from subscription to getYoutubeData, use pipe & map operators:

import { catchError, map } from 'rxjs/operators';

getYoutubeData(ch): any {
  let m="https://www.googleapis.com/youtube/v3/channels? 
  part=snippet%2CcontentDetails%2Cstatistics&id=" + ch + "&key=" + api;
  return this.http.get(m).pipe(
    map(data => data.items["0"].statistics),
    catchError(err => {
      console.log(err);
    });
  )
}

Upvotes: 1

ebeg
ebeg

Reputation: 428

You already subscribe in getYoutubeData method. You can only subscribe once. In your method please use pipe and tab method like :

getYoutubeData(ch):any{
  let m="https://www.googleapis.com/youtube/v3/channels? 
  part=snippet%2CcontentDetails%2Cstatistics&id=" + ch + "&key=" + api ;
  return this.http.get(m).pipe(tap(data =>
  { 
   this.youtubeObj=data.items["0"].statistics;
   return this.youtubeObj;
 }))
}

Upvotes: 0

joka00
joka00

Reputation: 2537

The problem here is that you can't basically return data from subscribe. So the solution here would be just returning an Observable and getting data in the constructor of the component.

.service.ts

 getYoutubeData(ch):any{
  let m="https://www.googleapis.com/youtube/v3/channels? 
  part=snippet%2CcontentDetails%2Cstatistics&id=" + ch + "&key=" + api ;
  return this.http.get(m);
}

*.component.ts

constructor(private db:FirebaseService,private afauth:AuthService) { 
  this.db.getDataObj("/Profile/" + this.uid).subscribe(res =>{
     this.profileInfo= res;
     this.afauth.getYoutubeData(res.channel).subscribe(data =>{
       console.log(data.items["0"].statistics);
  })
})}

Upvotes: 0

Related Questions