I will give you an asnwer based on my opinion and how I learnt. So don't take it for the absolute truth, but rather question it !
First, you should know that in Typescript, there's two ways of making async calls : Promises and Observables.
Promises are native in ES6, Observables are part of Rx JS.
But which one to use ?
Since it's my opinion, I will tell you to use Observables, because
- They can be stopped
- They can be played again
- They have lot of useful operators
- They can handle several values
All of this, Promises can't do.
Making an API call
Import the module
Very simple : first, you need to import the module responsible for that :
import { HttpClientModule } from '@angular/common/http';
// ...
imports: [HttpClientModule]
This is the new and improved http service in Angular 5. I highly recommend you to use it, since the older one (Http
) will soon be obsolete.
Use the HttpClient service
Now, in your services, you can use the HttpClient
like so
import { HttpClient } from '@angular/common/http';
// ...
constructor(
private http: HttpClient
) {}
// ...
getAny(): Observable<any> {
return this.http.get<any>('url'); // request options as second parameter
}
Use the business service
In your component, you can now do
import { MyService } from '../myservice/myservice.service';
// ..
constructor(private myService: MyService) {
this.myService.getAny().subscribe(() => {});
}
// ..
Complementary information
Handling errors or loaders
Say you want to show a progress bar, or handle errors : to do that, you will have to use Interceptors. Interceptors are services that will catch your request before (or after) sending it, and will do something.
Here is a simple interceptor for errors :
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ErrorHandlerService implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(req)
.catch(err => {
console.log('error occured');
return Observable.throw(err);
});
}
}
To use it, simply provide it with your value in your module :
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorHandlerService, multi: true }
]
I think you guessed, but you can use it to handle progress bars also ;)
Subscribing to an Observable and using async
As you've seen before, you can subscribe to an http call.
If you want to handle specific errors and do some logic in your component, here is how :
myService.getAny().subscribe(
responseAfterSuccess => {},
responseAfterError => {}
);
With this code, you will handle the success and the error.
Last thing, the async pipe : the async pipe transforms an Observable into data. To use it, do so
this.myVar = myService.getAny();
Your variable myVar
will contain an Observable. Now, in your HTML, with this
<div *ngFor="let item of myVar | async">{{ item }}</div>
Angular will wiat for data to arrive before displaying anything, and will transform the Observable into data, as if you did it by hand.