简体   繁体   English

返回值,而不是将结果放入变量中。 角度2

[英]Return value instead of putting the result inside a variable. Angular2

This code below going to load json file asynchronously and insert the result inside the _values variable. 下面的代码将异步加载json文件并将结果插入_values变量中。

private getValue(name) {
this.http.get('http://localhost:8080/getValue/' + name)
  .subscribe(res => this._values = res.json());
}

What I want is just to return one value, like normal JS function. 我想要的只是返回一个值,就像普通的JS函数一样。 I don't want the result to be stored inside variable. 我不希望结果存储在变量中。 I just want the function to return a value. 我只希望函数返回一个值。

Thank you in advance. 先感谢您。

Try this. 尝试这个。

 private getValue(name) : any {
    return this.http.get('http://localhost:8080/getValue/' + name)
                    .map(res => res.json());
 }

OR : 要么 :

 import 'rxjs/add/operator/toPromise';

 private getValue(name) : Promise<any>{
        return this.http.get('http://localhost:8080/getValue/' + name)
                        .toPromise()
                        .then(response => response.json());
 } 

then you would call this method with 那么您将使用

Promise<any> myvar = getValue(name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM