get请求
1、在app.module.js中引入模块并声明
import {HttpClientModule} from '@angular/common/http';
imports: [
HttpClientModule
],
2、在组件中引入模块并声明
import {HttpClient} from '@angular/common/http
constructor(private http: HttpClient) { }
3、调用函数
ngOnInit(){
let url='请求的路径'
// subscribe: 利用rxjs封装的http获取异步请求的数据,类似于promise
this.http.get(url).subscribe((data: any) => {
// data:返回的数据
});
}
post请求
1、在app.module.js中引入模块并声明
import {HttpClientModule} from '@angular/common/http';
imports: [
HttpClientModule
],
2、在组件中引入模块并声明
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
constructor(private http: HttpClient) { }
3、调用函数
ngOnInit(){
// 设置请求头
const httpOptions = {headers: new HttpHeaders({'Content-Type': 'application/json' })}
let url='请求的路径'
// subscribe: 利用rxjs封装的http获取异步请求的数据,类似于promise
this.http.post(url,{json数据},httpOptions).subscribe((data: any) => {
// data:返回的数据
});
}
jsonp跨域请求
1、在app.module.js中引入模块并声明
import {HttpClientModule, HttpClientJsonpModule} from '@angular/common/http';
imports: [
HttpClientModule,
HttpClientJsonpModule
],
2、在组件中引入模块并声明
import {HttpClient} from '@angular/common/http
constructor(private http: HttpClient) { }
3、调用函数
ngOnInit(){
let url='请求的路径'
// subscribe: 利用rxjs封装的http获取异步请求的数据,类似于promise
this.http.jsonp(url,'回调函数名称callback或cb').subscribe((data: any) => {
// data:返回的数据
});
}