Angular4-Http、Jsonp、rxjs请求

https://blog.csdn.net/u013318615/article/details/78962128

Http请求

依赖注入

import { HttpModule} from "@angular/http";
  • 1

页面引入Http

import { Http} from "@angular/http";
constructor(private http:Http)
 {
 }
  • 1
  • 2
  • 3
  • 4

get请求

 this.http.get(url).subscribe(function(data)
    {
      console.log(data['_body']);
      // JSON.parse(data["_body"]);
    },function(err)
    {
      console.log(err);
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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);
 });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Jsonp请求

依赖注入

import { JsonpModule} from "@angular/http";
imports: [
    JsonpModule,
  ],
  • 1
  • 2
  • 3
  • 4

页面引入Jsonp

import { Jsonp} from "@angular/http";
constructor(private jsonp:Jsonp)
{
}
  • 1
  • 2
  • 3
  • 4

get请求

 this.jsonp.get(url).subscribe(function(data)
 {
   console.log(data["_body"]);
 },function(err)
 {
   console.log(err);
 });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

rxjs请求

依赖注入

import { Observable} from "rxjs";
import "rxjs/Rx";
  • 1
  • 2

使用map方法

扫描二维码关注公众号,回复: 3683099 查看本文章
this.http.get(url).map(res => res.json()).subscribe(function(data)
{
   console.log(data);
 },function(err)
 {
   console.log(err);
 });

--------------------- 作者:Jzd_dev 来源:CSDN 原文:https://blog.csdn.net/u013318615/article/details/78962128?utm_source=copy 版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/fangquan1980/article/details/82998640