axios for angular code example

Example 1: how to install axios in react

$ npm install axios

Example 2: axios js and react

import React from 'react';

import axios from 'axios';

export default class PersonList extends React.Component {
  state = {
    persons: []
  }

  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
      .then(res => {
        const persons = res.data;
        this.setState({ persons });
      })
  }

  render() {
    return (
      <ul>
        { this.state.persons.map(person => <li>{person.name}</li>)}
      </ul>
    )
  }
}

Example 3: how to install axios in react

$ yarn add axios

Example 4: angular material mat-error on http request

// first define our formcontrol object
control = new FormControl('', [Validators.required])

//http method:
submit() {
  //call api
  // assume you got an error (Unauthorized, BadRequest, ...)
  //this set control to errored status and thus,
  //mark formcontrol/formgroup as invalid
  this.control.setErrors({error_key: true})
}

// in your html code :
<mat-form-field>
  <mat-label>Control</mat-label>
  <input type="text" formControlName="control" matInput />
  <mat-error *ngIf="control.hasError('required')">
  	Control cannot be empty
  </mat-error>
  <mat-error *ngIf="control.hasError('error_key')">
  	My custom error message
  </mat-error>
</mat-form-field>