【问题标题】:How do I fetch a json response from ionic-native HTTP get method?如何从 ionic-native HTTP get 方法获取 json 响应?
【发布时间】:2017-11-22 10:22:26
【问题描述】:

我正在学习 Ionic,我已经开始使用一些 API,现在我在使用 CountryAPI (https://fabian7593.github.io/CountryAPI/) 时遇到了一些问题。我正在使用 GET 方法接收一个包含所有名称中包含“统一”的国家/地区信息的 json。这是我的代码:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import firebase from 'firebase'
import { HTTP } from '@ionic-native/http'    

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  public resultados: any

  constructor(public navCtrl: NavController, public http: HTTP) {
    this.mget()
  }

  sair(){
    firebase.auth().signOut().then(() => this.navCtrl.setRoot('login'))
  }


  mget(){

    let url = 'http://countryapi.gear.host/v1/Country/getCountries?pName=united'

    this.http.get(url, {}, {}).then( data => {

      console.log(data.data); // data received by server

      let results = JSON.parse(data['_body']).results

    })
  }

}

当我 console.log 收到的数据以 json 格式显示时,一切正常且美观,但无法订阅 ionic-native http.get 方法,如果我尝试类似

for(let i = 0; i < news.length(); i ++){
      console.log(news[i])
      this.noticias.push({
        name: news[i].name,
        nativeName: news[i].nativeName
      })
    }

不好,它指责news.length()不是一个函数。

我需要获取向量中的所有数据,以便可以在我的应用中使用 ion-list 将其显示在列表中。

【问题讨论】:

  • 你只需要news.length不需要括号..
  • Array.length 是属性而不是函数

标签: javascript json typescript ionic-framework ionic2


【解决方案1】:

要从国家/地区 API 获取 JSON 数据,您应该像这样添加提供程序:

ionic g provider countryService

然后在 countryService.ts 中像下面的代码一样点击 API

  // ******************************** listing API ***********************************
  load() {

    console.log(' RestServiceProvider Load Method fro listing');
    if (this.data) {
      return Promise.resolve(this.data);
    }

    // don't have the data yet
    return new Promise(resolve => {
      this.http.get("http://countryapi.gear.host/v1/Country/getCountries?pName=united")
        .map(res => res.json().response)
        .subscribe(data => {
          this.data = data;
          resolve(this.data);
        });
    });
  }

要获取国家/地区的名称,您应该在 HomePage 中调用此方法,如下所示:

  this.countryService.load().then(data => {
        this.country= data;
      });

使用 HomePage 类的 html 在 UI 中显示名称:

 <ion-list>
        <ion-item *ngFor="let countrylist of country">
          <h2 style="color: tomato">User Id: {{countrylist.name}}</h2>
          <h4>{{countrylist.nativeName}}</h4>
        </ion-item>
      </ion-list>

【讨论】:

  • ionic 的本机 HTTP 插件中没有 map 方法,当我使用 angular 的 http 时,我遇到了无法摆脱的 CORS 错误。
猜你喜欢
  • 1970-01-01
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
  • 2015-09-08
  • 2019-07-31
相关资源
最近更新 更多