1.在app.module.ts中引入htpp:
import { HttpModule,JsonpModule } from '@angular/http';
(HttpModule模块用于get,post方法; JsonpModule模块用于jsonp请求)
2.在app.module.ts里的 imports注入HttpModule,JsonpModule模块:
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
NewComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
HttpClientModule,
//注入到这里
HttpModule,
JsonpModule,
NgZorroAntdModule
],
providers: [{ provide: NZ_I18N, useValue: zh_CN },StorageService],
bootstrap: [AppComponent]
})
3.还要在使用的文件里引入(这里是new组件new.component.ts里引用):
import { Http,Jsonp } from '@angular/http';
4.还要在使用的文件里引入(这里是new组件new.component.ts里引用):
import { Http,Jsonp,Headers} from '@angular/http';
注:这里引入的是Http,Jsonp不加Module,app.module.ts中引入的是 HttpModule,JsonpModule
5.在文件new.component.ts里声明到constructor构造函数参数里:
export class NewComponent implements OnInit {
//可分别通过私有变量private声明赋值给自定义变量
constructor(private http:Http,private jsonp:Jsonp) { }
ngOnInit() {
}
}
6.请求数据
import { Component, OnInit } from '@angular/core';
//post方法请求数据要引入Headers
import { Http,Jsonp,Headers } from '@angular/http'; /*数据请求模块*/
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
public list:any[]; //声明变量存放获取的数据
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http:Http,private jsonp:Jsonp,) { }
ngOnInit() {
//初始化完成就执行jsonpData方法请求数据
this. requestJsonpData()
}
//get请求数据
requestData(){
var _that=this;
// alert('请求数据');
var url="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
this.http.get(url).subscribe(function(data){
// console.log(JSON.parse(data['_body']));
var list=JSON.parse(data['_body']);
// console.log(_that.list['result']);
_that.list=list['result'];
},function(err){
console.log(err);
})
}
***//jsonp请求数据(可跨域)***
requestJsonpData(){
// jsonp 必须得在url加回到 &callback=JSONP_CALLBACK
var _that=this;
var url="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK";
this.jsonp.get(url).subscribe(function(data){
console.log(data);
/ _that.list=data['_body']['result'];
},function(err){
console.log(err);
})
}
//post请求数据
postData(){
// 1.import { Http,Jsonp,Headers } from '@angular/http'; Headers 定义请求头的
//2.private headers = new Headers({'Content-Type': 'application/json'});
//3.post提交数据
var url="http://127.0.0.1:3000/dologin";
this.http.post(url,
JSON.stringify({"username":'zhangsan',"age":'20'}),
{headers:this.headers}).subscribe(function(data){
console.log(data);
},function(error){
console.log(error);
})
}
}