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

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

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

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

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

...   ...

imports:[

...  ...

HttpModule,

JsonpModule  ]


《news.component.html》:

       

  •  {{item.title}}


法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":'这是后台返回的新闻数据'});

})

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'});  

//设置请求头

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);

})

}


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