我在函数中调用了一个数组,它是空的,为什么?
I call an array in a function and it is void, why?
这是我的 .ts 代码:
array:any = [];
OnClickFunction(){
this.httpClient.get<any[]>("http://url/?lbs="+this.my variable,{responseType: 'json'})
.subscribe(data => {
this.array = data;
console.log(this.array)// This array contain many data
});
console.log(this.array)// this call of this array contain nothing, why ???
这是 Tsvetan Ganev 用图片表示的内容:
数字表示操作顺序。
#1。代码发出http get请求,是异步的。
#2。执行订阅后的行,控制台记录局部变量当前未定义。
#3。在稍后的某个时间点,当异步调用 returns 响应时,将执行订阅(回调)中的代码并将响应数据分配给局部变量。
希望对您有所帮助。
这是演示异步管道以及它如何为您管理对 observable 的订阅的完美场所。
array$: Observable<any[]>;
OnClickFunction(){
this.array$ = this.httpClient.get<any[]>("http://url/?lbs="+this.my variable,{responseType: 'json'});
}
并在您的模板中使用
<ng-containter *ngIf="array$ | async as array">
{{ array | json }} Inside here you have your array available
</ng-container>
这是我的 .ts 代码:
array:any = [];
OnClickFunction(){
this.httpClient.get<any[]>("http://url/?lbs="+this.my variable,{responseType: 'json'})
.subscribe(data => {
this.array = data;
console.log(this.array)// This array contain many data
});
console.log(this.array)// this call of this array contain nothing, why ???
这是 Tsvetan Ganev 用图片表示的内容:
数字表示操作顺序。
#1。代码发出http get请求,是异步的。
#2。执行订阅后的行,控制台记录局部变量当前未定义。
#3。在稍后的某个时间点,当异步调用 returns 响应时,将执行订阅(回调)中的代码并将响应数据分配给局部变量。
希望对您有所帮助。
这是演示异步管道以及它如何为您管理对 observable 的订阅的完美场所。
array$: Observable<any[]>;
OnClickFunction(){
this.array$ = this.httpClient.get<any[]>("http://url/?lbs="+this.my variable,{responseType: 'json'});
}
并在您的模板中使用
<ng-containter *ngIf="array$ | async as array">
{{ array | json }} Inside here you have your array available
</ng-container>