Currently, I'm faced with a task that requires me to fetch 10 Chuck Norris jokes from an API. While I managed to accomplish this part, I'm struggling with the second part of the task, which involves retrieving a random joke every 5 seconds.
// Fetch jokes based on quantity
getJokes(amount) {
const jokeArray = [];
let randomJokeArray;
if (amount > 1){
this.http.get('http://api.icndb.com/jokes/random/' + amount).subscribe(data => {
// Check if API call was successful
if (data["type"] === 'success'){
for(let i = 0; i <= data["value"].length; i++){
jokeArray.push(data["value"][i]);
}
} else {
console.warn("API Call 'getJokes' failed");
}
});
} else {
this.http.get('http://api.icndb.com/jokes/random/' + amount).subscribe(data => {
// Check if API call was successful
if (data["type"] === 'success'){
randomJokeArray = data["value"][0];
console.log(randomJokeArray);
} else {
console.warn("API Call 'getJokes' failed");
}
});
}
if (amount > 1){
// Return the jokeArray
return of(jokeArray);
} else {
return of(randomJokeArray);
}
}
The issue is that randomJokeArray
always returns as undefined.
This function is implemented within a service, and as someone relatively new to TypeScript and Angular, it's likely that I am using it incorrectly. Could someone please guide me on how to retrieve just one joke from the API?
If I replicate the API call for fetching 10 jokes, it works fine, but when trying to get only one joke, I face the following problem.
From the main file
this.configService.getJokes(1).subscribe(j => this.randomJokeArray = j);
From the service file
for(let i = 0; i <= data["value"].length; i++){
randomJokeArray.push(data["value"][i]);
}
return of(randomJokeArray);