Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

asynchronous - Properly use Async calls with Angular 5

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.

  • making an API call using ( async - try - catch )
  • how to 'subscribe' to that call in a Component level

Thank You !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...