我想从api获取数据并将其分配给我的变量。
在订阅中,我为subscribe
中的变量和控制台记录的变量分配了数据。一切正常,变量现在具有数据,但是在subscribe
结束后,busDepotLocality仍将是未定义的。试图让超时等待,但是什么都没有
app.component.ts:
busDepotLocality: BusDepotLocality;
ngOnInit() {
this.mapService
.getBusDepotLocality()
.subscribe((data: BusDepotLocality) => {
this.busDepotLocality = data;
console.log(data); // Data is showing, no problem
console.log(this.busDepotLocality); //Assignment passed, data is showing, no problem
});
console.log(this.busDepotLocality); // But after all busDepotLocality will be undefined
答案 0 :(得分:0)
尝试:
async ngOnInit() { // Step 1
await this.mapService // Step 2
.getBusDepotLocality()
.toPromise().then((data: BusDepotLocality) => {
this.busDepotLocality = data; // Step 3
console.log(data); // Data is showing, no problem
console.log(this.busDepotLocality); //Assignment passed, data is showing, no problem
});
console.log(this.busDepotLocality); // Step 4
}
要弄清如何在生命周期挂钩中进行异步等待,请按以下步骤操作:
1)在步骤1中,我们使钩子异步,因此它不会妨碍/影响此生命周期钩子,因为我们不在步骤1中等待此方法调用,它将继续执行其他循环事件
2)在第2步中,我们一直等到得到响应,等待之后的任何代码行都将等到我们获得异步调用(“ http”调用)的响应
3)在步骤3中,我们得到响应。
4)在步骤4中,我们执行其余语句。
PS:由于这里我们要求在一切完成后执行语句并获得最终响应,因此需要将其转换为Promise。
并且,如果您坚持认为是可观察的,则可以在html中使用异步管道
\\ Component
private data:Observable<any>;
ngOnInit(){
this.data=this.mapService.getBusDepotLocality();
}
\\ HTML
{{data|async}}
否则,您可以通过管道发送(tap())您的响应
答案 1 :(得分:0)
您正在尝试记录尚未填充的内容。
作为证明,请尝试
busDepotLocality: BusDepotLocality;
ngOnInit() {
this.mapService
.getBusDepotLocality()
.subscribe((data: BusDepotLocality) => {
this.busDepotLocality = data;
console.log(data); // Data is showing, no problem
console.log(this.busDepotLocality); //Assignment passed, data is showing, no problem
},(error) => {console.log(error)},() => {console.log(this.busDepotLocality); });
答案 2 :(得分:0)
为了了解您遇到的问题,您需要更好地了解订阅。以我现在想到的最简单的方式,考虑一个像实时流这样的订阅,这意味着只要您正在流化内容,就可以访问数据。现在,将这个概念应用于您遇到的问题,我们有以下代码:
busDepotLocality: BusDepotLocality;
ngOnInit() {
this.mapService
.getBusDepotLocality()
.subscribe((data: BusDepotLocality) => {
this.busDepotLocality = data;
console.log(data); // Data is showing, no problem
console.log(this.busDepotLocality); //Assignment passed, data is showing, no problem
});
console.log(this.busDepotLocality); // But after all busDepotLocality will be undefined
您实际上用评论表明了我的观点-在订阅中可以访问数据,在订阅之外,无法分配数据。您可能想映射数据,然后在每次访问数据时订阅该变量。例如:
busDepotLocality: BusDepotLocality;
ngOnInit() {
this.busDepotLocality = this.mapService
.getBusDepotLocality()
.pipe(map((data) => data));
const results = this.busDepotLocality.subscribe(val =>
console.log(val)
//code goes here
);
}