I have been googling for a few days and found many different scenarios about how to use Async API calls with Angular 5 ( or 2-3-4, whatever ).
Can anyone give me some correct example ( some good use-case ) about it?
ex.
Thank You !
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.
Since it's my opinion, I will tell you to use Observables , because
All of this, Promises can't do.
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.
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
}
In your component, you can now do
import { MyService } from '../myservice/myservice.service';
// ..
constructor(private myService: MyService) {
this.myService.getAny().subscribe(() => {});
}
// ..
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 ;)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.