npm install axios --save
- 创建一个服务
ng g service services/httpservice
- 在app.module.ts引入封装的axios服务
import { HttpserviceService } from './services/httpservice.service';
providers: [StorageService, HttpserviceService],
- 在httpservice文件内写以下内容
import axios from 'axios';
import { Observable } from 'rxjs';
get(api: any) {
/* return new Promise((resolve, reject) => {
axios
.get(api)
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
}); */
return new Observable((observe) => {
axios
.get(api)
.then((response) => {
observe.next(response);
})
.catch((error) => {
observe.error(error);
});
});
}
在要调用的ts文件就可以写请求
// 引入使用axios获取数据
import { HttpserviceService } from '../../services/httpservice.service';
constructor(public axiosHttp: HttpserviceService) {}
getAxiosData() {
let api = 'http://a.itying.com/api/productlist';
/* this.axiosHttp.get(api).then((res) => {
console.log(res);
}); */
this.axiosHttp.get(api).subscribe((response) => {
console.log(response);
});
}