ng4.x http数据请求 --- 使用RxJS

【此例通过Http、Jsonp请求数据  ----  使用RxJS】

RxJS:是一种针对异步数据流编程工具,后者叫响应式扩展编程;---- 异步编程】

《app.module.ts》:   ----  数据请求模块 的引入及依赖注入

import { HttpModule, JsonpModule } from '@angular/http';

...   ...

imports:[

...  ...

HttpModule,

JsonpModule  ]


法1:--- get请求

《news.component.ts》:

import {Http} from '@angular/http';

import { Observable } from "rxjs";

import 'rxjs/Rx';

export class NewsComponent implements OnInit {

public list :any[];

constructor(private http:Http) {   }

ngOnInit() { 

  this.requestData();

 }

requestData() {

var _that = this;

var url = "http://www.phonegap100.com/appapi.php?a=getPortallList&catid=20&page=1";

this.http.get(url).map(res=>res.json()).subscribe( function (data){

var list = _that.list = JSON.parse(data['_body']);

_that.list = list['result'];

},function(err){

alert(err);

})

}..

法2:--- jsonp请求  --- 后台不允许跨域

《news.component.ts》:

import { Http,Jsonp} from '@angular/http';

import { Observable } from "rxjs";

import 'rxjs/Rx';

export class NewsComponent implements OnInit {

public list :any[];

constructor(private http:Http,private jsonp:Jsonp){}

}

ngOnInit() {  }

requestData() {

var _that = this;

var url = "http://127.0.0.1:3000/news?&callback=JSONP_CALLBACK";

this.jsonp.get(url).map(res=>res.json()).subscribe( function (data){

_that.list =data['_body']['result'];

},function(err){

alert(err);

})

}..

nodejs 后台接口:

《app.js》:

app.get('/news',function(req,res){

res.jsonp({"msg":'这是后台返回的新闻数据'});

})

法3:--- post请求

《news.component.ts》:

import {Http,Header} from '@angular/http';

import { Observable } from "rxjs";

import 'rxjs/Rx';

export class NewsComponent implements OnInit {

private header = new Headers({'Content-Type' : 'application/json'});

//设置请求头

public list :any[];

constructor(private http:Http){}

}

ngOnInit() {  }

postData() {

var _that = this;

var url = "http://127.0.0.1:3000/dologin";

this.http.post(url,

JSON.stringify({ "username":'xj'}),

{headers:this.hraders}).subscribe(function(data){

},function(err){

alert(err);

})

}..

你可能感兴趣的:(ng4.x http数据请求 --- 使用RxJS)