Angular中的数据交互(get , jsonp , post )
一 Angular中的get 请求数据
Angular5.x以后get , post 和服务器交互使用的是HttpClientModule模块
使用步骤:
- 在app.module.ts中引入HttpClientModule
import { HttpClientModule } from '@angular/common/http' ;
- 在使用到的地方引入HttpClient 并在构造函数中声明 // 当作一个服务
import { HttpClient } from '@angular/common/http' ;
constructor( public http:HttpClient ){}
3.get请求数据
var api = "http://b.itying.com/api/productlist";
this.http.get(api).subscribe(res =>{
console.log(res)
}
二 post提交数据
-
在app.module.ts中引入HttpClientModule
-
在使用到的地方引入HttpClient , HttpHeaders 并在构造函数中声明
3.post提交数据 // 需手动设置请求类型 ,设置请求头
const httpOptions = {
headers : new HttpHeaders({
'content-Type' : 'application/json'
})
};
//存在跨域,需后端允许跨域
var api = "http://b.itying.com/api/productlist";
this.http.post(api , {username :"张三", age:"20"},httpOptions ).subscribe(res => {
console.log(res)
})
三 jsonp获取数据
1.引入HttpClientModule , HttpClientJsonpModule
2.引入HttpClient
3.jsonp请求数据
//jsonp请求 服务器必须支持jsonp, 在地址后加callback
var api = "http://b.itying.com/api/productlist";
this.http.jsonp(api , 'callback' ).subscribe(res => {
console.log(res)
})
四 使用第三方模块axios请求数据 //同其他框架的使用,如vue 等
-
安装axios
-
在用到的地方引入axios
import axios from ‘axios’;