简体   繁体   English

Angular http 获取调用保存对变量的响应?

[英]Angular http get calls saving response to a variable?

I'm a bit new to angular and I have a problem where I can console.log the response from a "get", but when I try to save it to a variable, the variable is always empty.我对 angular 有点陌生,我有一个问题,我可以控制台记录来自“get”的响应,但是当我尝试将它保存到变量时,变量总是空的。 Something to do with it being asynchronous I think because I see the console trying to print out the response variable before it prints out data from inside the subscribe.我认为它与异步有关,因为我看到控制台在从订阅内部打印数据之前试图打印出响应变量。 This is just bare bones code but I think it demonstrates my problem.这只是简单的代码,但我认为它说明了我的问题。

response;

constructor(private http: HttpClient) {
this.getResponse();
console.log(response);
}

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

In this example, the second console log, console.log(data), prints out the appropriate response but the first one, console.log(response), is blank.在此示例中,第二个控制台日志 console.log(data) 打印出适当的响应,但第一个控制台日志 console.log(response) 为空白。 What's frustrating is every single stack overflow response I've found about using http get simply console logs the response instead of showing how to properly store the response and access it later?令人沮丧的是我发现使用 http 的每一个堆栈溢出响应都只是简单地控制台记录响应,而不是显示如何正确存储响应并在以后访问它? What do I need to do to store the response from the get into a variable and then be able to work with that variable?我需要做什么才能将 get 的响应存储到变量中,然后才能使用该变量?

try it like this, and try to check rather you get an response from your request像这样尝试,并尝试检查您是否从您的请求中得到响应

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);
);
}

I recommend implementing your backend call in ngOnInit.我建议在 ngOnInit 中实现你的后端调用。 Http requests are async tasks, which means it takes some time getting the response, thats why yur first console.log(response) is null because the answer hasnt happened yet. Http 请求是异步任务,这意味着它需要一些时间才能得到响应,这就是为什么你的第一个 console.log(response) 是 null 因为答案还没有发生。 If you want to store the receiving data, try this:如果要存储接收数据,请尝试以下操作:

  response;

  constructor(private http: HttpClient) {

  }

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

}

You can also work with promises and await the response but you dont have to, this should work您也可以使用承诺并等待响应,但您不必这样做,这应该可以

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

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