【此例通過Http攒发、Jsonp請求數(shù)據(jù)? ---- ?使用RxJS】
【RxJS:是一種針對異步數(shù)據(jù)流編程工具呼伸,后者叫響應(yīng)式擴展編程柒莉;---- 異步編程】
《app.module.ts》: ? ---- ?數(shù)據(jù)請求模塊 的引入及依賴注入
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":'這是后臺返回的新聞數(shù)據(jù)'});
})
法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'});
//設(shè)置請求頭
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);
})
}..