首页 文章

无法使用IONIC 2生成的提供程序从RESTFUL API接收数据

提问于
浏览
0

所以,我正在研究Ionic 2来制作混合应用程序 . 我正在学习关于Udemy的课程,但是关于对WEB API的HTTP请求的课程内容已经过时(它来自离子2 Beta) . 这是一个很长的问题,但是你们中有些人对Ionic 2框架更有经验,可以跳到第8步以节省一些时间 . 非常感谢!

我正在尝试从此URL检索数据:

https://viacep.com.br/ws/01001000/json/ .

It has a space after https:// because stackoverflow won't allot me to post more than one link. 但是我错过了将这些数据保存在我创建的变量上的东西 .

我在这一点上所做的是:

1)我使用CLI离子生成器生成了我称为ConnectionService的提供程序 .

ionic g provider ConnectionService

2)在ConnectionService Provider中创建了一个名为getCEP()的方法,该方法生成 HTTP GET Request

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the ConnectionService provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ConnectionService {

  constructor(public http: Http) {
    console.log('Hello ConnectionService Provider');
  }

  getCep(): Promise<Response>{
      let response: any = this.http.get("https://viacep.com.br/ws/01001000/json/");
      console.log("Response: " + response);
      let responsePromise: any = response.toPromise();
      console.log("ResponsePromise: " + responsePromise);
      return responsePromise;
  }
}

P.S.: Here you can see i'm loggin in two steps of the request: The first one is the response before I turn it into a Promise, so I can return it to the page. The second one is after i cast it to a Promise using the toPromise() method.

3)在我的视图中,我有一个按钮,它具有调用方法buscarCEP()的(click)指令

<ion-header>

  <ion-navbar>
    <ion-title>Teste</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
  <button (click)="buscarCep()">Request CEP</button>

</ion-content>

4.1)我的TypeScript文件已导入ConnectionService Provider并将其命名为ConnectionService .

4.2)我在“providers:”标签下的@Component指令中声明了ConnectionService

4.3)我创建了一个Connection Provider的实例,我在构造函数的声明中调用conServ . 我还创建了一个名为CEP的变量来存储我从中提取的数据 .

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ConnectionService } from '../../providers/connection-service';

/*
  Generated class for the MenuTest page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-menu-test',
  templateUrl: 'menu-test.html',
  providers: [ConnectionService]
})
export class MenuTestPage {
  public CEP: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public conServ: ConnectionService) {
  }

6)然后我修改方法buscarCEP(),以便它获取conServe实例并调用getCEP()方法,该方法对上面给出的URL发出HTTP请求 .

buscarCep(): void{
    this.conServ.getCep().then(data =>{
      console.log("DATA:" + data);
      this.CEP = data;
    }).catch(err => {
      console.log("ERRO: " + err);
    });
    console.log("CEP: " + this.CEP);
  }

PS.: As you can see, i'm logging three steps into the request: The data when the getCEP() method executes, a possible error called 'err' and by the end of it, the variable CEP that I created before and saved the data value to.

7)当我运行应用程序并单击按钮时,我将使用console.logs获得以下屏幕:

离子页面的图像与Chrome控制台的剪辑
Image of ionic page with snips of the Chrome console

8)正如您所看到的,我的日志返回如下:8.1)"Hello ConnectionService Provider"来自提供程序构造函数内的console.log,因此提供程序的导入很好并且正在实例化 . 8.2)"Response: [object Object]"来自提供者本身的getCEP()方法内的第一个console.log() . 8.3)"RespondePromise: [object Object]"来自提供者本身的getCEP()方法内的第二个console.log(),之后我将响应转换为Promise . 8.4)"CEP: undefined"来自buscarCEP()方法内的console.log,在我点击Request CEP按钮8.5后调用 . “DATA:状态响应:200 OK,URL:https://viacep.com.br/ws/01001000/json/”来自console.log( )在buscarCEP()方法中 .

9)由此我认为getCEP()方法能够连接到URL,因此Response和ResponsePromise日志为什么附加了一个Object . DATA日志也告诉我,我收到了来自服务器的OK响应 . 我的问题是关于CEP:未定义的日志 . 我似乎无法将该对象存储在我创建的变量中 .

我知道这是一个很长的问题,但我想把所有的牌都放在棋盘上并尽可能彻底地解释所有内容,因为我是这个框架的新手 .

感谢您的帮助,谢谢您的时间!

1 回答

  • 0

    Response object 存储在 this.CEP 中 . 问题是在 then 中返回HTTP请求的响应之前调用 console.log(this.CEP) .Promises是异步的 . 您可以通过在 then 内执行 console.log(this.CEP) 来检查内容 . 因此,如果您要在html端打印数据,请使用安全导航操作符 ? . 例如: {{CEP?.property}} .

    您的代码有几个问题:

    • 您应该从响应对象中提取json数据 . 我建议你这样做: this.CEP = data.json();

    • 如果要打印对象的内容,可以尝试 console.log(JSON.stringify(data,null,2)) .

相关问题