I have a recursive JavaScript that I am using in angular 19 to pull data from YouTube. The script is working, but is there a better way to do it?
public getSeriesList() {
this.record.webTubeSeries = [];
this._seqNum = 0;
this.getUrlYouTube()
.pipe(first())
.subscribe({
next: (res: any) => {
this.parseVideoList(res["items"]);
if (res['nextPageToken']) {
let repeatGetNextVideoPage = (_token: string) => {
this.getNextVideoPage(_token)
.subscribe(
(result: any) => {
this.parseVideoList(result["items"]);
if (result["nextPageToken"]) {
repeatGetNextVideoPage(result["nextPageToken"]);
}
}
),
(err: any) => {
console.log("HTTP Error", err.message)
}
}
repeatGetNextVideoPage(res["nextPageToken"]);
}
}
}
);
}
private getNextVideoPage(_token: string) {
let url = (this.urlYouTube + this.videoListId + '&pageToken=' + _token);
return this.http.get(url);
}
private parseVideoList(result: any) {
for (let v of result) {
var item = new WebtubeSeries;
item.videoTitle = v.snippet.title;
item.videoId = v.snippet.resourceId.videoId;
if (v.snippet.thumbnails) {
item.urlThumbNailDefault = v.snippet.thumbnails.default.url;
item.urlThumbNailMedium = v.snippet.thumbnails.medium.url;
item.urlThumbNailHigh = v.snippet.thumbnails.high.url;
item.widthDefault = v.snippet.thumbnails.default.width.toString();
item.heightDefault = v.snippet.thumbnails.default.height.toString();
item.widthMedium = v.snippet.thumbnails.medium.width.toString();
item.heightMedium = v.snippet.thumbnails.medium.height.toString()
item.widthHigh = v.snippet.thumbnails.high.width.toString()
item.heightHigh = v.snippet.thumbnails.high.height.toString();
item.seqNumber = this._seqNum++;
//item.id = item.seqNumber;
this.record.webTubeSeries.push(item);
}
}
}
2
Answers
To test it, you need a key from Youtube. You can use my existing videolistId or you can use your own one. Thanks.
In angular19 they have introduced
resource
andrxResource
which can be used for data handling based on input signals. I am suggesting this approach usingrxResource
since we can leverage rxjs to perform the recursion.Recursively calling an API using RxJS expand operator
First we define the construction of the class logic inside the class constructor.
Then, we can define the
rxResource
with a property calledloader
which makes the API call.Inside the loader, we use
expand
which is used for recursive API calls, we also usetakeUntil
to stop the sequence, when there is no next API token.Finally, we merge the results using
reduce
and construct the final result.Full Code:
Stackblitz Demo