实例在 angulardemo07:
/ *angular get请求数据
1.在app.module.ts中引入HttpClientModule:import {HttpClientModule} from ‘@angular/common/http’;
2.在app.module.ts中声明HttpClientModule:imports: [ HttpClientModule ]
3.在用到的ts引入 HttpClient:import {HttpClient} from “@angular/common/http”;
4.在用到的ts的构造函数中声明HttpClient对象:HttpClient:constructor(public http:HttpClient) { }
5.在用到的html中监听事件,在ts中获取事件方法,调用http.get(要请求的接口)收到请求数据.subscribe()处理数据
6.进行处理。
*/
/ *angular jsonp获取服务器数据
1.在app.module.ts中引入 :import {HttpClientModule,HttpClientJsonpModule} from ‘@angular/common/http’;
2.在app.module.ts中声明:imports: [HttpClientModule,HttpClientJsonpModule]
3.在用到的ts引入:import {HttpClient} from “@angular/common/http”;
4.在用到的ts的构造函数中声明HttpClient对象:constructor(public http:HttpClient) { }
5.在用到的html中监听事件,在ts中获取事件方法,调用http.jsonp(要请求的接口)收到请求数据.subscribe()处理数据
6.进行处理。
*/
/ *angular post提交数据
1.在app.module.ts中引入HttpClientModule:import {HttpClientModule} from ‘@angular/common/http’;
2.在app.module.ts中声明HttpClientModule:imports: [ HttpClientModule]
3.在用到的ts引入 HttpClient:import {HttpClient,HttpHeaders} from “@angular/common/http”;
4.在用到的ts的构造函数中声明HttpClient对象:HttpClient:constructor(public http:HttpClient) { }
5.在用到的html中监听事件,在ts中获取事件方法,调用http.post(要提交的接口数据)提交数据.subscribe()处理
*/
/*也可以用第三方模块axios
1.安装axios模块:npm install axios
2.封装服务,在service中引入:import axios from ‘axios’;
3.在service.ts中封装方法(方法名自定义):
axiosGet(api:any){
return new Observable((observer:any)=>{
axios.get(api).then(function(response){
observer(response);
});
});
}
4.使用时在app.module.ts里引入HttpserviceService,并声明providers: [HttpserviceService]
5.在需要使用的component.ts里引入HttpserviceService,并在构造器中声明对象public httpService:HttpserviceService
6.在html中监听getAxiosData()事件
getAxiosData(){
var api="http://a.itying.com/api/productlist";
// this.httpService.axiosGet(api).subscribe((data:any)=>{
// console.log(data);
// });
axios.get(api).then((data)=>{
console.log(data);
});
}
7.在getAxiosData()里获取数据即可
*/