将http post响应数据分配为字符串形式的变量

问题描述 投票:0回答:3

是离子的新手。我正在使用http请求从服务器获取url,它会返回正确的数据作为响应。但是返回数据并不会以字符串形式分配给变量。

这是我的代码

 url:any;

 constructor(public http: Http, public stor :Storage) {
        //if i set the variable manually it works.
       // this.url="http://myipadd/project";

        this.geturl().then(res => {
           this.url= res; 

           //output of the console log is "http://myip/projecctindepage"
           console.log(this.url); 


 });
 //output of this is "undefined"
 console.log(this.url);

 }

功能

geturl(){

    return new Promise(resolve => {
      this.http.get('http://url/index.php/getip/getpublicip')
        .map(res => res.json())
        .subscribe((data: any) => {
          this.result = data;
          this.items = JSON.stringify(this.result);
          console.log(this.items);
          this.allData = JSON.parse(this.items);
          console.log("check json data "+this.allData["data"]);
          resolve (this.allData["data"]);   
        }, );
      });

}

check0,check1和check2的控制台输出为check0:对象承诺检查1:192.168.9.5/index.php/admin/getip“ check2:192.168.9.5/index.php/admin/getip”

我想做的是将“ 192.168.9.5/index.php/admin/getip”设置为字符串的baseUrl变量。

我在这里做错了什么?

angular ionic-framework ionic3
3个回答
1
投票

我在想两件事。您的getUrl返回一个promise,而不是字符串,因此您应该能够执行此操作。

this.getUrl().then((url: string) => { this.baseurl = url; }

或者..您可以从http请求中设置基本URL,因为您订阅了结果,因此实际上不需要返回承诺。

subscribe((data: any) => { this.baseurl = data.data; }

代码示例:

    geturl(){
     return new Promise(resolve => {
         this.http.get('http://localhost/mechmarcl_website/index.php/Admin/getpublicip')
             .map(res => res.json())
             .subscribe((data: any) => {

                 // you receive the data here, so you can use the data here
                 // For example:
                 this.baseurl = data.data;

                 // what you tried to do here I think with this line?
                 this.url= JSON.stringify(data.data);

                 resolve ((data.data));
             }, error => {
             resolve(error);
             });
     });
   }

或承诺方式。

constructor(public http: Http) {
     this.geturl().then((url: string) => {
        this.baseurl = url;
     }, (err: any) => {
       // handle your promise rejection here
     }
    });
   }

0
投票

您需要使用then()来兑现承诺:

this.geturl().then(url => this.baseurl = url);


0
投票

您可以使用以下内容:this.geturl().then(url => this.baseurl = url.toString());

或者您可以选择:

let baseurl = await this.geturl();
this.baseurl = baseurl.toString();

但是我认为第一个将完成这项工作。@Anton Mitsev代码看起来也很有希望。

© www.soinside.com 2019 - 2024. All rights reserved.