How do I wait for an HttpClient subscription to wrap up before returning the data in Angular 18

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 = "";
  }
}

1

The code inside the subscribe is asynchronous (waits for the API), but the code below it is synchronous (does not wait for the API). So you need to move the code below the subscribe into the subscribe, so that it executes after the API call is made. In your service, the return happens before the API completes this is the root cause of the issue.


Subscribe to the API on the component instead of on the service.

  retrieveCard(name: string, set?: string): Observable<Cards> {
    let card: Cards = {}

    return this.queryApi(`cards/named?exact=${name}${typeof set != undefined ? `&set=${set}` : ""}`)
    .pipe(map((json) => {
      card[json["id"]] = {
        name: json["name"],
        qty: 1,
        set: json["set"],
        imageURL: json["image_uris"]["png"]
      }
      return card; // <- notice!
    })
  );

  }
  

Then get the data on the component using subscribe, this will give you the exact result always.

export class AddCardsComponent {
  constructor(private apiService: ApiService) {}
  private tempCollection: Collection = { cards: {} };
  name: string = "";
  set: string = "";

  addTempCard(): void {
    this.apiService.retrieveCard(this.name.toLowerCase(), this.set?.toLowerCase()).subscribe((card: Cards) => {
      console.log(card);
      console.log(Object.keys(card)[0]);
      this.name = "";
      this.set = "";
    });
  }
}

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật