Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
角度-如何获取http get请求的json值?_Json_Angular - Fatal编程技术网

角度-如何获取http get请求的json值?

角度-如何获取http get请求的json值?,json,angular,Json,Angular,所以我正在尝试建立一个非常基本的应用程序,在localhost上有一个Angular项目,从localhost上的另一个项目获取json 我有一个方法服务 get() { var returnVal; this.http.get('http://localhost:8080/getAll).subscribe((response: Response) => returnVal = response.json()) return returnVal; } 当my sub.c

所以我正在尝试建立一个非常基本的应用程序,在localhost上有一个Angular项目,从localhost上的另一个项目获取json

我有一个方法服务

get() {
    var returnVal;
    this.http.get('http://localhost:8080/getAll).subscribe((response: Response) => returnVal = response.json())
return returnVal;
}

当my sub.component.ts将其分配给变量时,它将返回未定义的,并且不会在html上显示任何内容,此时它将返回json。

Http Get是一个异步调用,在Get方法完成之前返回returnVal。您可以在异步调用中返回值,或者等待promise解析。 例如:


角度返回异步观测中的HTTP调用-在调用完成后,即在执行行“return-returnVal”之后,将调用subscribe

为了更好地理解角度应用程序,您应该使用这种异步特性,而不是试图以同步方式等待它。例如,在组件类型脚本中:

valueFromServer: any = null; // This should be set to an actual type, not any, ideally.

onButtonPress() {
    this.http.get('http://localhost:8080/getAll').subscribe((response: Response) => {
        this.valueFromServer = response.json();
    });
}
然后在组件模板中,使用以下值执行操作:

<button (click)="onButtonPress()">Load</button>
<p *ngIf="valueFromServer">{{valueFromServer}}</p>
<p *ngIf="!valueFromServer">Not loaded yet.</p>
加载
{{{valueFromServer}

尚未加载


启动异步操作(HTTP GET)并在异步结果初始化之前返回一个值。考虑使用Auth.HTTP方法是异步的。code>return语句发生在将任何值赋给
returnVal
之前。使用
wait
或返回值的
Observable
,并在需要实际值时向其订阅
subscribe
<button (click)="onButtonPress()">Load</button>
<p *ngIf="valueFromServer">{{valueFromServer}}</p>
<p *ngIf="!valueFromServer">Not loaded yet.</p>