angular请求数据常用的方法有两种,一种是自带的http模块,一种是用第三方的axios。
http模块
先说一下自带的http模块如何使用,需遵循以下步骤:
1、在app.module.ts中引入HttpClientModule模块并注入
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';//引入http模块
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule //注入
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
2、在用到的地方引入HttpClient并在构造函数中声明
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http'; //引入
@Component({
selector: 'app-woman',
templateUrl: './woman.component.html',
styleUrls: ['./woman.component.css']
})
export class WomanComponent implements OnInit {
constructor(private http:HttpClient) { //在构造函数中声明
}
ngOnInit(): void {
let url = '/api/users/list';
this.http.get(url).subscribe(res=>{//调用http模块
console.log(res)
})
}
}
如果是post请求,我们还需要额外引入HttpHeaders这个请求头模块:
import { Component, OnInit } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-woman',
templateUrl: './woman.component.html',
styleUrls: ['./woman.component.css']
})
export class WomanComponent implements OnInit {
constructor(private http:HttpClient) {
}
ngOnInit(): void {
// let url = '/api/users/list';
// this.http.get(url).subscribe(res=>{
// console.log(res)
// })
let url = '/api/users/detail';
const headerMsg =
this.http.post(url,{id:123},{headers:new HttpHeaders({'Content-Type':'application/json'})}).subscribe(res=>{
console.log(res);
});
}
}
axios模块
1、安装axios。
cnpm install axios -S
2、新建service。
ng g service services/httpservice
httpservice.service.ts:
import { Injectable } from '@angular/core';
import request from '../../utils/request.js';
console.log(request)
@Injectable({
providedIn: 'root' //将服务注入到root根组件时,可以不用在app.module的providers再声明了
})
export class HttpserviceService {
constructor() { }
getList(url){//发请求
return new Promise((resolve,reject)=>{
request.get(url).then(res=>{
resolve(res)
}).catch(e=>{
reject(0)
})
})
}
}
这里需要注意@Injectable()装饰器,如果里面声明了注入到root根组件,就表示在全局注册单例service,这样可以不用在app.module.ts中再注入一次了;反之则需要。保险起见,还是两个地方都声明一下。
request.js:
import axios from "axios"
let instance = axios.create({
headers: {
'content-type': 'application/json'
}
})
// http request 拦截器
instance.interceptors.request.use(
config =>{
console.log('request拦截')
//alert(localStorage.getItem('accessToken'))
config.headers.AccessToken = 'hello,123'
//config.headers.test = '123'
return config
},
err => {
return Promise.reject(err)
})
// http response 拦截器
instance.interceptors.response.use(
response => {
console.log('这是response拦截');
//拦截响应,做统一处理
if (response.data.code === 201005 || response.data.code === 201006) {
//销毁accessToken
localStorage.removeItem('accessToken')
location.href ='/' //去首页重新获取accessToken
}
return response
},
//接口错误状态处理,也就是说无响应时的处理
error => {
return Promise.reject(error.response.status) // 返回接口返回的错误信息
})
export default instance
3、在app.module.ts中注入service。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpserviceService } from './service/httpservice.service';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule
],
providers: [HttpserviceService], //如果在service声明了@Injectable({providedIn: 'root'}),这里可以省略
bootstrap: [AppComponent]
})
export class AppModule { }
4、使用service。
import { Component, OnInit,ViewChild } from '@angular/core';
import { HttpserviceService } from '../../service/httpservice.service';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
constructor(public httpservice:HttpserviceService) {
}
ngOnInit(): void {
}
//代理转发
getData(){
let url = '/api/users/list';
this.httpservice.getList(url).then(res=>{
console.log(res)
})
}
}
代理
在本地调试的时候需要打开代理服务,这个也很容易,我们单独建一个配置文件
config/config/proxy.conf.json:
{
"/api": {
"target": "http://localhost:3000/",
"secure": false,
"pathRewrite": {
"^/api": "/"
}
}
}
然后在package.json文件的script配置项指定一下:
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config ./config/proxy.conf.json",
"build": "ng build"
},