Angular comes with an HTTP module to facilitate HTTP requests. You don’t have to install and configure Axios as Vue does.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {

  constructor(private http: HttpClient) { }
  
  ngOnInit() {// initiate a get request this.http.get()'/api/people/1').subscribe(json => console.log(json)); }}Copy the code

Note: above this.http. Get… Handling HTTP is best done in a separate Service file and injected into the Component. I didn’t do that for the sake of demonstration.

Optimize multiple requests that have sequential dependencies

Sometimes we need to make multiple requests in order, using some of the results returned by the first request as parameters for the second request, such as the code below.

  ngOnInit() {
    this.http.get('/api/people/1').subscribe(character => {
      this.http.get(character.homeworld).subscribe(homeworld => {
        character.homeworld = homeworld;
        this.loadedCharacter = character;
      });
    });
  }
Copy the code

The above nested writing method is not very readable, and we can optimize the above code by using the mergeMap operator provided by RxJS

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { mergeMap } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {
  homeworld: Observable<{}>;
  constructor(private http: HttpClient) { }
  
  ngOnInit() {
    this.homeworld = this.http.get('/api/people/1') .pipe( mergeMap(character => this.http.get(character.homeworld)) ); }}Copy the code

The mergeMap operator is used to get a value from an internal Observable and return it to the parent stream object. You can merge Observables

Processing concurrent requests

ForkJoin is the Rx version of Promise.all(), which means that it waits until all Observables have completed before returning a value once.


import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { forkJoin } from "rxjs/observable/forkJoin";

@Component({
  selector: 'app-root',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {
  loadedCharacter: {};
  constructor(private http: HttpClient) { }
  
  ngOnInit() {
    let character = this.http.get('https://swapi.co/api/people/1');
    let characterHomeworld = this.http.get('http://swapi.co/api/planets/1'); forkJoin([character, characterHomeworld]).subscribe(results => { // results[0] is our character // results[1] is our character homeworld results[0].homeworld = results[1]; this.loadedCharacter = results[0]; }); }}Copy the code

The online demo

Error handling request

To handle an Error in an Observable using catchError, either return a new Observable or throw an error

In example 1, the error is handled internally in the request method. If the request fails and a default value is returned, the user does not seem to be aware that an error has occurred

  // http.service.ts
  getPostDetail(id) {
    return this.http
    .get<any>(`https://jsonplaceholder.typicode.com/posts/${id}').pipe(// catchError requires a new Observable or throwing an error. CatchError (err => { (Try to change to the wrong address)return of({
            userId: 1,
            id: 1,
            title: '-occaecati excepturi optio reprehenderit-',
            body: '-eveniet architecto-'}); }))} // ComponentgetPostDetail() {
    this.postDetail$ = this.service.getPostDetail(1)
    .subscribe(val => {
      console.log(val);
    });
  }

Copy the code

Example 2 throws the error directly and handles the error externally, such as with a popover informing the user

  getPostDetail(id) {
    return this.http
    .get<any>(`${this.endpoint}/posts2/${id}`) .pipe( // catchError returning a new observable or throwing an error. catchError(err => { throw err; }))} // Modify the calling methodgetPostDetail() { this.postDetail$ = this.service.getPostDetail(1) .subscribe( (next) => { }, => {// add your own error handling logic, make a popover, notify, etc console.log(err); })}Copy the code

reference

Use RxJS to handle multiple Http requests