[英]Angular http get calls saving response to a variable?
我對 angular 有點陌生,我有一個問題,我可以控制台記錄來自“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 的響應存儲到變量中,然后才能使用該變量?
像這樣嘗試,並嘗試檢查您是否從您的請求中得到響應
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 請求是異步任務,這意味着它需要一些時間才能得到響應,這就是為什么你的第一個 console.log(response) 是 null 因為答案還沒有發生。 如果要存儲接收數據,請嘗試以下操作:
response;
constructor(private http: HttpClient) {
}
ngOnInit() {
return this.http.get(URL).subscribe((data) => {
this.response = data;
console.log(response);
);
}
}
您也可以使用承諾並等待響應,但您不必這樣做,這應該可以
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.