Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5 httpClient and Promises

I've been looking at Angular 5's GET POST etc:

get() {
    return this.httpClient.get<any>('https://api.github.com/users/seeschweiler');
}

or

http.get<ItemsResponse>('/api/items')
    .subscribe(
       // Successful responses call the first callback.
       data => {...},
       // Errors will call this callback instead:
       err => {
         console.log('Something went wrong!');
       });

I don't see that promises are usually used with it.

Is this because it's not really needed or some other reason?


2 Answers

Angular by defaults uses Observables. Observables give you more flexibility working with streams.

If you want to work with Promises you can still cast Observable into Promises by using toPromise function.

like image 107
Suren Srapyan Avatar answered Sep 19 '25 19:09

Suren Srapyan


February 2024

toPromise() function call is now deprecated and we should be using firstValueFrom() or lastValueFrom() like so:

import { lastValueFrom } from 'rxjs';

return lastValueFrom(this.httpClient.get<any>(url));

returns a promise

like image 29
java-addict301 Avatar answered Sep 19 '25 18:09

java-addict301