角度 http 得到调用保存对变量的响应?



我对 angular 有点陌生,我有一个问题,我可以控制台.log来自"get"的响应,但是当我尝试将其保存到变量时,变量总是空的。我认为这与它是异步的有关,因为我看到控制台在从订阅内部打印出数据之前尝试打印出响应变量。这只是简单的代码,但我认为它证明了我的问题。

response;
constructor(private http: HttpClient) {
this.getResponse();
console.log(response);
}
getResponse() {
return this.http.get(URL).subscribe((data) => {
this.response = data;
console.log(data);
);
}

在此示例中,第二个控制台日志 console.log(data( 打印出相应的响应,但第一个控制台日志 console.log(response( 为空。令人沮丧的是,我发现关于使用 http get 的每个堆栈溢出响应都只是控制台日志响应,而不是显示如何正确存储响应并在以后访问它!我需要做什么才能将来自 get 的响应存储到变量中,然后能够使用该变量?

尝试这样做,并尝试检查,而不是从请求中得到响应

let response: string = "blue";
constructor(private http: HttpClient) {
this.getResponse();
console.log(response);
}
getResponse() {
return this.http.get(URL).subscribe((data) => {
this.response = data.toString;
console.log(data);
);
}

我建议在ngOnInit中实现后端调用。Http 请求是异步任务,这意味着需要一些时间来获取响应,这就是为什么您的第一个控制台.log(响应(为空,因为答案尚未发生。如果要存储接收数据,请尝试以下操作:

response;
constructor(private http: HttpClient) {
}
ngOnInit() {
return this.http.get(URL).subscribe((data) => {
this.response = data;
console.log(response);
);
}
}

您也可以使用承诺并等待响应,但您不必这样做,这应该有效

最新更新