返回值而不是将结果放在变量中。 Angular2

时间:2016-12-08 16:13:29

标签: javascript angular

下面的代码将异步加载json文件并将结果插入_values变量中。

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

我想要的只是返回一个值,就像普通的JS函数一样。我不希望结果存储在变量中。我只想让函数返回一个值。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个。

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

或者:

 import 'rxjs/add/operator/toPromise';

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

然后你会用

调用这个方法
Promise<any> myvar = getValue(name);
相关问题