我有一个函数fetchLyrics
,它命中一个服务并订阅它,我当前将它用作子组件的Output事件。
fetchLyrics($event) {
console.log($event);
this.apiService.get($event.artist, $event.song)
.subscribe(
(res) => {
console.log(res);
return res['lyrics'];
},
(err) => {
console.log(err);
return err;
}
);
}
我想在getSuggestions
getSuggestions(term) {
this.apiService.suggest(term)
.debounceTime(2000)
.subscribe(
(res) => {
console.log(res);
for (const item of res['data']) {
const grab = this.fetchLyrics({
artist: item.artist.name,
song: item.title,
});
console.log(grab);
item.playing = false;
}
this.songs = res['data'];
},
(err) => {
this.songs = [];
console.log(err);
}
);
但是当我检查我的控制台日志时,我看到grab
在undefined
res['data']
答案 0 :(得分:0)
您的fetchLyrics方法不会返回任何内容,实际上它会订阅某些服务,一旦数据返回,您就会返回响应。
subscribe(Observable)不起作用,它将等待服务返回数据,然后它将执行subscribe块,所以一旦你调用fetchLyrics方法,observable就会出现异步任务,你将得到未定义。
你应该做的是:
fetchLyrics($event) {
console.log($event);
return this.apiService.get($event.artist, $event.song)
.map((res) => {
console.log(res);
return res['lyrics'];
});
}
得到如下建议:
getSuggestions(term) {
this.apiService.suggest(term)
.debounceTime(2000)
.subscribe(
(res) => {
console.log(res);
for (const item of res['data']) {
this.fetchLyrics({
artist: item.artist.name,
song: item.title,
}).subscribe(
(res) => {
console.log(res);
item.playing = false;
},
(err) => {
console.log(err);
}
);
this.songs = res['data'];
},
(err) => {
this.songs = [];
console.log(err);
});