angular axios used to initiate http request

angular used axios

/**
 * Http introduced using third-party modules in the angular, for example to axios
 * There are two methods used herein :( Promise using simple encapsulation)
 * A component to be used directly in the requested import axios from 'axios', call: axios.get / axios.post ...
 . * Package into two services: 
 * 1. 引入 axios: import axios from 'axios'
 * 2. promise rxjs optionally with a callback function in three ways one encapsulated
 */

 

1. axios.service.ts in

import { Injectable } from '@angular/core';
import axios from 'axios'   
@Injectable({
  providedIn: 'root'
})
export class AxiosService {
  constructor() { }
  AxiosGet ( fire ) {
    return new Promise((resolvereject)=>{
      axios.get(api).then((res)=>{
        resolve(res)
      })
    })
  }
}

2. 根模块中注入:

import { AxiosService } from '../service/axios.service'

 

providers: [AxiosService]

 

3. 组件中使用:

// 引入服务
import { AxiosService } from '../../service/axios.service'
@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
  public newsList: any[]
  constructor(public $axios: AxiosService) { }
  ngOnInit() {
  }
  axiosGetData() {
    let url = '/search/interface/getrelatequery?word=%E6%99%8B%E6%B1%9F'
    this.$axios.AxiosGet(url).then((data)=>{
      console.log("axios GET 请求: "data)
    })
  }
}
 

 

Guess you like

Origin www.cnblogs.com/monkey-K/p/11621801.html