【此例通過Http污淋、Jsonp請求數(shù)據(jù)? ----? 不用RxJS】
【RxJS:是一種針對異步數(shù)據(jù)流編程工具大审,或者叫響應式擴展編程芥牌;---- 異步編程】
《app.module.ts》: ? ---- ?數(shù)據(jù)請求模塊 的引入及依賴注入
import { HttpModule, JsonpModule } from '@angular/http';
... ? ...
imports:[
... ?...
HttpModule,
JsonpModule ?]
《news.component.html》:
<button (click) = "requestData()">請求數(shù)據(jù)</button>
<ul >
? ? <li *ngFor="let item list"> ?{{item.title}}</li>
</ul>
法1:--- get請求
《news.component.ts》: ?
import { Http } from '@angular/http';
export class NewsComponent implements OnInit {
public list :any[];
constructor(private http:Http){}
}
ngOnInit() { ?}
requestData() {
var _that = this;
var url = "http://www.phonegap100.com/appapi.php?a=getPortallList&catid=20&page=1";
this.http.get(url).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';
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).subscribe( function (data){
_that.list =data['_body']['result'];
},function(err){
alert(err);
})
}
nodejs 后臺接口:
《app.js》:
var express = require('express');
var app=express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/news',function(req,res){
? ? ?res.jsonp({"msg":'這是后臺返回的新聞數(shù)據(jù)'});
})
app.listen(3000,'127.0.0.1');
法3:--- post請求
《news.component.ts》:
import { Http,Headers } from '@angular/http';
export class NewsComponent implements OnInit {
private headers = 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){
? ? ? ? ? console.log(data.json());
},function(err){
alert(err);
})
}