如何调用具有文本文件的URL,将其转换为字符串并在离子2中显示?

时间:2016-09-27 13:33:01

标签: angular ionic2

我想做的就是调用一个包含文本格式数据的URL,将其转换为字符串变量,然后在我的ionc 2 app中将其作为消息或toast输出。 到目前为止,我的应用程序显示了按钮,但是当我单击它以激活setMessage()函数时,它根本不会显示任何内容。

到目前为止我的代码看起来像这样。

这是我的about.html

<ion-header>
  <ion-navbar primary>
    <ion-title>
      Sismos 
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding class="about">
<button (click)="setMessage()"> Button</button>

</ion-content>

这是我的about.ts文件

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';


//La libreria de abajo la importé para conectarme al Catalogo de Sismos
// el link es http://www.prsn.uprm.edu/Data/prsn/EarlyWarning/Catalogue.txt
//import {Http} from '@angular/http';



@Component({
  templateUrl: 'build/pages/about/about.html'
})
export class AboutPage {

                           message: any;
                           // items: any;
                                                        constructor(public navCtrl: NavController, private http: Http)
                            {       
                              //  this.items = [];
                             }

     setMessage() {
                                                   let URL_Data = this.http.get('http://www.prsn.uprm.edu/Data/prsn/EarlyWarning/Catalogue.txt');
                                let message = URL_Data.toString();
                                                   return message;
                                           }               

                        }

1 个答案:

答案 0 :(得分:0)

你正在返回一个字符串,但没有做任何事情。您设置了message但未在页面上显示。

尝试在html f.e中设置一个变量。 <p>{{message}}</p>(如果使用此功能,请不要忘记初始化您的邮件,message:string = "no message available";

在您的.ts文件中

...//imports, component decorator

export class AboutPage{
  message:string = "no message yet";

  ..... //constructor etc.

  setMessage(){
    this.http.get("url").subscribe(response => {

        this.message = response.toString();

        //asynchronous method converting the returned Observable
        //(http.get returns Observable) and setting it to the message property.
    });
    //note that, code here will be executed BEFORE the subscribe method (asynchronous)
    //so make sure everything you need to do with the message or response is in the subscribe()
  }


}