无法评估来自 .subscribe 外部的 http post 响应数据

Cannot assess the http post response data from outside of the .subscribe

我正在使用 http 请求从服务器获取 url,它 returns 正确的数据作为响应。将数据设置为变量后,我无法通过其他方法访问变量数据。

这是我的代码

public  urlcheck:any;

constructor(public http: Http) {

   //what i want to do is something like this, it works when i do like this.
   //urlcheck = "http://10.0.2.2/mysite/";


   this.urlcheck = this.http.get('http://localhost/website/index.php/Admin/getpublicip');
   this.urlcheck.subscribe(data => {
      //console output is  ('my data: http://10.0.2.2/mysite')
      console.log('my data: ', data["_body"]);
      this.urlcheck = data["_body"];

   })
//console output is ("check url[object Object]")
console.log("check url"+this.urlcheck);
}

我做错了什么?

您需要使用 then() 来解决承诺:

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

我认为你混淆了两件事。你的 getUrl return 是一个承诺,而不是一个字符串,所以你应该能够做到这一点。

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

或者..您可以从您的 http 请求中设置 baseurl,因为您订阅了结果,因此实际上不需要 return 承诺。

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
     }
    });
   }

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

或者你可以选择:

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

但我认为第一个就可以了。 @Anton Mitsev 代码看起来也很有前途。