Best practice when awaiting an RxJS API call?

Discussão em 'Angular' iniciado por sirzento, Fevereiro 10, 2025.

  1. sirzento

    sirzento Guest

    I already know about 3 methods to return a Promise<T> when doing an API call.

    // Method 1
    return this.http.get<DataType>(`api/call`).toPromise();

    // Method 2
    return firstValueFrom(this.http.get<DataType>(`api/call`));

    // Method 3
    return new Promise<DataType>((res, rej) => {
    this.http.get<DataType>(`api/call`).subscribe((data: DataType) => {
    res(data);
    });
    });


    .toPromise() is deprecated and should not be used anymore. Method 2 looks short and clean. Method 3 does the job, but it's quite a bit more code.

    Are there other methods to convert that API call to a promise or is method 2 the way to go nowadays?

    Continue reading...

Compartilhe esta Página