我试图从另一个使用youtube API发送HTTP请求的组件中获取信息,但出现此问题:
Cannot read property 'subscribe' of undefined
at SafeSubscriber._next (profile.page.ts:20)
这是组件代码,我从这里尝试从服务中获取信息:
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);
})
})}
这是发送http请求的服务功能代码:
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;
})
}
答案 0 :(得分:1)
您需要通过删除订阅并返回getYoutubeData
来更正服务中的this.http.get
方法。要从订阅data.items["0"].statistics
中获得getYoutubeData
,请使用pipe
和map
运算符:
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);
});
)
}
答案 1 :(得分:0)
您已经使用getYoutubeData
方法进行订阅。您只能订阅一次。在您的方法中,请使用管道和制表符方法,例如:
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;
}))
}
答案 2 :(得分:0)
这里的问题是,您基本上不能从subscribe
返回数据。因此,这里的解决方案将只是返回一个Observable
并在组件的构造函数中获取数据。
.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);
})
})}