ionic3.x 中的数据请求

get 请求数据

在 app.module.ts 引入 HttpModule 、JsonpModule

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

在 app.module.ts 依赖注入 HttpModule 、JsonpModule

imports: [
    BrowserModule,
    ComponentsModule,
    HttpModule,
    JsonpModule,
    //IonicModule.forRoot(MyApp);
    IonicModule.forRoot(MyApp,{
      tabsHideOnSubPages:true,
      backButtonText:'返回'
    })
  ],

在需要请求数据的地方引入 Http

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

构造函数内申明

constructor(public http: Http, public jsonp: Jsonp,public navParams: NavParams)

对应的方法内使用 http 请求数据

getData() {
    var that = this;
    this.http.get(this.url).subscribe(function(data){
      that.list = JSON.parse(data['_body']).result[0];
      console.log(that.list);
    }, function(err){
      console.log(err);
    });
  }

在html文件中绑定数据

{{list.title}}

JSONP请求

this.url = 'http://www.phonegap100.com/appapi.php?a=getPortalArticle&aid='+aid+'&callback=JSONP_CALLBACK';
getData() {
    var that = this;
    this.jsonp.get(this.url).subscribe(function(data){
      that.list = data['_body'].result[0];
      console.log(that.list);
    }, function(err){
      console.log(err);
    });
  }

用JSONP请求时需要在URL最好加上&callback=JSONP_CALLBACK,另外请求的数据格式也有变化,解析的时候需要注意;
另外,请求回调方法也可写成(data)=>{}的形式:

getData() {
    var that = this;
    this.jsonp.get(this.url).subscribe((data)=>{
      that.list = data['_body'].result[0];
      console.log(that.list);
    }, function(err){
      console.log(err);
    });
  }

post请求数据

引入 Headers 、Http 模块

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

实例化 Headers

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

post 提交数据

this.http .post('http://localhost:8008/api/test', JSON.stringify({username: 'admin'}), {headers:this.headers}) // .toPromise()
.subscribe(function(res){
 console.log(res.json()); 
});

你可能感兴趣的:(ionic3.x 中的数据请求)