I’m working with Angular 18 and I’m trying to query data from an API so I can store it inside my component. I’m able to successfully console.log
the API data stored in my object with both my component and the service that I’m using to retrieve the data. However, whenever I try to console.log
its key or any of its values on their own, undefined
shows up in the console. In addition, using Object.keys
with the object returns an empty array.
I found a similar stackoverflow post here, and while it says that the issue stems from the opened object in the console not accurately depicting its current value, I’m not sure how to fix the issue. I tried looking into ways to delay the data I receive from my query’s subscription, so that I can store the data into the variable before the rest of the code executes. Sadly though, the only stuff I found was what I had already been trying. Making it so that the object require the this
keyword to be used didn’t help either. I don’t want to use async/await if I can help it because I don’t want to have to deal with returning Promises, but I can if there is no other way.
tldr: How do I wait for an HttpClient
subscription to wrap up before returning the data from the API its querying?
api.service.ts
export class ApiService {
constructor(private httpClient: HttpClient) { }
private collection: Collection = { cards: {} };
queryApi(query: string): Observable<Data> {
return this.httpClient.get<Data>(`https://api.scryfall.com/${query}`);
}
retrieveCard(name: string, set?: string): Cards {
let card: Cards = {}
this.queryApi(`cards/named?exact=${name}${typeof set != undefined ? `&set=${set}` : ""}`)
.subscribe((json) => {
card[json["id"]] = {
name: json["name"],
qty: 1,
set: json["set"],
imageURL: json["image_uris"]["png"]
}
});
return card;
}
}
add-cards.component.ts
export class AddCardsComponent {
constructor(private apiService: ApiService) {}
private tempCollection: Collection = { cards: {} };
name: string = "";
set: string = "";
addTempCard(): void {
const card: Cards = this.apiService.retrieveCard(this.name.toLowerCase(), this.set?.toLowerCase());
console.log(card) // returns key and values
console.log(Object.keys(card)[0]) // returns undefined
this.name = "";
this.set = "";
}
}