完整的代码, 可以复制引用
appMoudel配置部分
// 导入HttpClient模块
import { HttpClientModule } from '@angular/common/http';
// 在NgModule中添加HttpClientModule到imports数组
imports: [
HttpClientModule
],
http文件部分
// 请求示例
import { HttpClient, HttpHeaders } from '@angular/common/http';
constructor(public http: HttpClient) { }
// 执行GET请求
this.http.get('http://a.itying.com/api/productlist').subscribe((res: any) => {
this.list = res.result;
console.log(res);
});
// 设置请求头
const headers = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
}
// 执行POST请求
this.http.post('http://1270.0.1:3000/doLogin', { usernmae: '张三', age: 20 }, headers).subscribe((res: any) => {
this.list = res.result;
console.log(res);
});
JSONP请求配置
// 在appMoudel中导入需要的模块
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';
// 在NgModule中添加到imports数组
imports: [
HttpClientModule,
HttpClientJsonpModule
],
// JSONP请求示例
// 注意: jsonp需要服务器支持,一般在API地址后添加?callback=xxx 或 cb=xxx
this.http.jsonp('http://a.itying.com/api/productlist', 'callback').subscribe((res: any) => {
this.list = res.result;
console.log(res);
});
封装请求方法示例
get(api) {
return new Promise((resolve, reject) => {
this.http.get(this.url + api).subscribe((res) => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
// 调用封装的方法
this.store.get('/appapi.php?a=getPortalList&catid=20&page=1').then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});