1. 1. 安装axios
    2. yarn add axios
    3. 2.建立axios服务
    4. import { Injectable } from '@angular/core';
    5. import axios from 'axios'
    6. import { Observable } from 'rxjs'
    7. axios.defaults.timeout = 5000;
    8. import { environment } from '../../environments/environment'
    9. console.log(environment.baseURL);
    10. axios.defaults.baseURL = environment.baseURL
    11. @Injectable({
    12. providedIn: 'root'
    13. })
    14. export class AxiosService {
    15. constructor() { }
    16. postfun(url:string,params:any){
    17. return axios.post(url,params)
    18. .then(response=>{
    19. if(response.status == 200){
    20. Promise.resolve(response.data)
    21. }
    22. }).catch(err=>{
    23. })
    24. }
    25. getfun(url:string,params={}){
    26. return new Promise((resolve,reject)=>{
    27. axios.get(url,{
    28. params:params
    29. })
    30. .then(res=>{
    31. resolve(res.data)
    32. })
    33. })
    34. }
    35. //RXJS进行数据请求
    36. getrxjsdata(){
    37. let url:string = 'http://a.itying.com/api/productlist'
    38. return new Observable((observer)=>{
    39. axios.get(url).then(res=>{
    40. observer.next(res)
    41. })
    42. })
    43. }
    44. }
    45. 3.引入服务
    46. import { AxiosService } from '../../service/axios.service'
    47. 4.注册
    48. constructor(public axios:AxiosService) { }
    49. 5.创建数据请求函数
    50. getInof(){
    51. let url:string = 'http://a.itying.com/api/productlist'
    52. this.axios.getfun(url,{name:'alci'}).then((res:any)=>{
    53. console.log(res.result);
    54. })
    55. }
    56. //在去调用即可调取函数
    57. 5-2或者使用rxjs
    58. getInof(){
    59. this.axios.getrxjsdata().subscribe((res:any)=>{
    60. console.log(res.data.result);
    61. })
    62. }
    63. //再去调用此函数即可