get 请求数据
-
在app.module.ts 中引入 HttpClientModule 并注入
//引入HttpClientModule import { HttpClientModule } from '@angular/common/http'; imports: [ BrowserModule, AppRoutingModule, HttpClientModule ],
-
在用到的地方引入 HttpClient, HttpHeaders并在构造函数声明HttpClient。
//当做一个服务 import { HttpClient, HttpHeaders } from '@angular/common/http'; constructor(public http:HttpClient) { }
-
get 请求数据
getData(){
// alert('执行get请求');
//服务器必须允许跨域
let api="http://a.itying.com/api/productlist";
this.http.get(api).subscribe((response:any) =>{
console.log(response);
this.list=response.result;
})
}
post 提交数据
-
在app.module.ts 中引入 HttpClientModule 并注入
//引入HttpClientModule import { HttpClientModule } from '@angular/common/http'; imports: [ BrowserModule, AppRoutingModule, HttpClientModule ],
-
在用到的地方引入 HttpClient, HttpHeaders并在构造函数声明HttpClient。
//当做一个服务 import { HttpClient, HttpHeaders } from '@angular/common/http'; constructor(public http:HttpClient) { }
-
post提交数据
const httpOptions = {headers: new HttpHeaders({'content-Type':'application/json'})};
//存在跨域
let api='http://127.0.0.1:3000/dologin';
this.http.post(api,{"username":"张三",'age':20},httpOptions).subscribe((response) =>{
console.log(response);
});
Jsonp 请求数据
import { HttpClientModule,HttpClientJsonpModule } from '@angular/common/http';
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
HttpClientJsonpModule
],
//当做一个服务
import { HttpClient, HttpHeaders } from '@angular/common/http';
constructor(public http:HttpClient) { }
getJsonpData(){
let api="http://a.itying.com/api/productlist";
this.http.jsonp(api,'callback').subscribe(response =>{
console.log(response);
});
}
使用第三方模块axios 请求数据
-
安装
npm install axios --save
-
引入
import axios from 'axios';
-
使用
//在服务中,处理方法
axiosGet(api:any){
return new Promise((resolve,reject)=>{
axios.get(api)
.then(function (response){
console.log(response);
});
})
//在组件中使用axios来获取数据
getAxiosData(){
let api="http://a.itying.com/api/productlist";
this.httpService.axiosGet(api).then((data:any)=>{
console.log('111');
})
}