为什么我不能在 get 请求之外打印数组地址 1?我被这个卡住了,有人能帮我吗?
我也尝试过使用 XMLHttpRequest (),即使它也显示了同样的问题。
从 “@ angular/common/http” 导入 {http client};
实现 OnInit {的导出类 MapComponent
私人元素 = [];
SearchURL = "http:.";
构造函数 (私有 http 客户端: http 客户端) {}
NgOnInit (): void {
变量地址 s1 = [];
Var i;
获取 (此。搜索 url)。订阅 (res: 任何 [) => {
元素 = res;
对于 (i = 0; i
this.httpClient.get
is of type observable so it is called asynchronously. console.log(address1[i]);
在它之外,所以这一行首先被执行。所以你没有得到结果
您可以访问address1[]
outside the request's subscription - it's declared in ngOnInit
并且生活在它的封闭中 -- 但是很明显,在请求有机会得到解决之前,你不会有任何内容。在请求完成之前,您的 “不在这里打印” 循环会被执行。
你好,因为你的代码在 Http 响应之前正在执行,所以要打印数据,请执行以下操作
从 “@ angular/common/http” 导入 {http client};
实现 OnInit {的导出类 MapComponent
私人元素 = [];
SearchURL = "http:.";
构造函数 (私有 http 客户端: http 客户端) {}
公众地址: 任何 = []
NgOnInit (): void {
变量地址 s1 = [];
获取 (此。搜索 url)。订阅 (res: 任何 [) => {
元素 = res;
对于 (让我 = 0; 我
`
如果你想在 html 文件中使用它,那么使用地址钥匙
`
这是由于 http.get 的异步行为造成的,所以如果你想在没有外部响应后使用地址 1 []。