Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios and Angular

Trying to figure out how to make an axios import and use in an Angular cli, base scaffolding.

I didn't find any docs for this.

I found this https://netbasal.com/angular-2-use-your-own-http-library-b45e51b3525e

what he suggests does not apply. the Cli breaks on adding any of his code bits.

Any insight on how to do a basic post api call in Angular?

best I got is (the angular native approach) :

import { Component } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

@Injectable()
export class AppComponent{
  title = 'prouuuut';
  posts = [];
  errors = [];
  constructor(private http: Http){
  }

  fetchAll(){
    this.http.get('https://api.github.com/repositories')
      .then(response => {
        this.posts = response.data.entry
      })
      .catch(e => {
        this.errors.push(e)
      })
  }
}

inside app.component.ts but I already have :

enter image description here

like image 757
tatsu Avatar asked Nov 03 '17 15:11

tatsu


People also ask

Can I use Axios with Angular?

Axios is also a promise-based HTTP client that can be used in plain JavaScript as well as in advanced JavaScript frameworks like React, Vue. js, and Angular.

Is Axios only for Nodejs?

Axios: Axios is a Javascript library used to make HTTP requests from node. js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6. It can be used intercept HTTP requests and responses and enables client-side protection against XSRF.

Is Axios front end?

Axios is supported by all major browsers. The package can be used for your backend server, loaded via a CDN, or required in your frontend application.

What is typescript Axios?

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase).


1 Answers

Most probably using Axios's concrete class instead of Angular's Http concrete class is not a valid approach since each of these classes would have a different interface.

You need to

  1. npm install @types/axios
  2. import axios as you import any other third-party library in typescript

Note that it is recommended to use Angular's Http Client Module

From axios github page:

axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular"

Angular's (Angular 2+) Http client is more powerful than Angular JS's Http client, so I could not think of a reason that requires you to be making this switch

like image 191
Yousof Sharief Avatar answered Sep 16 '22 21:09

Yousof Sharief