啦啦啦啦啦 我又来 的哈
今天我要说的是 ng中的 发送请求的事情,这个可是必须要讲解的 不然工作都没法进行 不是嘛 太多的理论废话 就不啰嗦了 上才艺
在 app.module.ts文件中 引入 http模块 不需要下载 是它内置的
import { HttpClientModule } from "@angular/common/http";
// 在下面的imports 中也设置一下
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
然后就是在组件中使用
import { HttpClient } from "@angular/common/http";
constructor(public http:HttpClient) { } // 赋值给当前属性
发送请求 我在本地开启了一个node服务器
this.http.get('//localhost:5000').subscribe((res)=>{
console.log(res);
})
看下控制台 数据也确实回来了哈
如果是想要带参数的话 是
在请求地址后面 加上一个 对象 {params:} 后面跟着的就是 要带的参数
this.http.get('//localhost:5000',{params:{name:"zhaoyunchong"}}).subscribe((res)=>{
console.log(res);
})
2.说完 get 请求就要说 post请求了
import { HttpClient } from "@angular/common/http";
this.http.post('//localhost:5000').subscribe((res) => {
console.log(res);
})
然后就是 axios在ng中的使用了 咋说了 可能是这个axios封装的太好了 vue react中都在用它 ng中也在用它 哈哈
axios 属于第三方的东西了 所以要用它 我们要下载好了
npm install axios --save
这个请求 我建议 封装到一个 服务中 然后 通过让组件引入 服务的方式 来使用axios
首先创建一个 服务器
ng g service service/http
// 引入 并且封装一个请求
import { Injectable } from '@angular/core';
import axios from "axios";
@Injectable({
providedIn: 'root'
})
export class HttpService {
constructor() { }
axiosGet(data){
return new Promise((resolve,reject)=>{
axios.get(data.url).then(res=>{
resolve(res.data);
})
})
}
}
然后就是在组件中使用了 不过使用 前 也别忘了 在 app.module.ts中注册 使用
import { HttpService } from "./service/http.service";
providers: [ HttpService ],
这下 才可以在组件中使用了
不过组件中 也要引入一次哈
import { HttpService } from "../../service/http.service";
constructor(public axios:HttpService) { }
引入和注册成功之后 就可以使用了
// 调用 我们在服务中 封装好的方法 传入地址
this.axios.axiosGet({ url:"//localhost:5000"}).then(res=>{
console.log(res);
})
数据也是正常回来了
关注我 持续更新前端知识