Http请求
依赖注入
import { HttpModule} from "@angular/http";
- 页面引入Http
import { Http} from "@angular/http";
constructor(private http:Http)
{
}
get请求
this.http.get(url).subscribe(function(data)
{
console.log(data['_body']);
// JSON.parse(data["_body"]);
},function(err)
{
console.log(err);
});
post请求
// 首先在页面引入Headers
import { Http,Headers} from "@angular/http";
// 实例化
header = new Headers({'Content-Type':'application/json'});
// post请求
var body = JSON.stringify({"account":"li","password":"123456"});
this.http.post(url,body,{headers:this.header}).subscribe(function(data)
{
console.log(data);
});
Jsonp请求
依赖注入
import { JsonpModule} from "@angular/http";
imports: [
JsonpModule,
],
页面引入Jsonp
import { Jsonp} from "@angular/http";
constructor(private jsonp:Jsonp)
{
}
get请求
this.jsonp.get(url).subscribe(function(data)
{
console.log(data["_body"]);
},function(err)
{
console.log(err);
});
rxjs请求
依赖注入
import { Observable} from "rxjs";
import "rxjs/Rx";
- 使用map方法
this.http.get(url).map(res => res.json()).subscribe(function(data)
{
console.log(data);
},function(err)
{
console.log(err);
});