iOS ajax请求用本地调用,angular 中发送ajax请求 自带的http模块和引入axios 你用那种?...

啦啦啦啦啦 我又来 的哈

今天我要说的是 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);

})

看下控制台 数据也确实回来了哈

74310ae685d9008c92286652e77568a7.png

如果是想要带参数的话 是

在请求地址后面 加上一个 对象 {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);

})

数据也是正常回来了

d79f97142f7cae840b5e154d74c064cf.png

关注我 持续更新前端知识

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值