【发布时间】:2019-07-04 20:31:27
【问题描述】:
以下代码给出了运行时错误,因为 top5Ids 未定义。当我正确订阅 observable 并从订阅者 next 方法内部设置 top5Ids 变量时,我真的不明白为什么这个变量是未定义的。
cryptoService 类只是返回 http.get() 函数的结果,它是一个 observable。
export class HomeComponent implements OnInit {
cryptoDetails: CryptoDetail[];
top5Ids: string[];
constructor(private cryptoService: CryptoService) { }
ngOnInit() {
this.cryptoDetails = new Array();
this.getTop5Crypto();
this.getCryptoData(this.top5Ids);
const source = interval(5000).subscribe(val => this.getCryptoData(this.top5Ids))
}
getCryptoData(ids: string[]){
this.cryptoDetails = [];
console.log("get crypto")
for(let id of ids){
this.cryptoService.getCryptoInfo(id).subscribe(res => {
let data = res.data;
let cryptoDetail = new CryptoDetail(data.id, data.rateUsd, data.symbol);
this.cryptoDetails.push(cryptoDetail);
})
}
this.cryptoDetails.sort();
}
getTop5Crypto() : void {
let top5CryptoIds : string[] = [];
this.cryptoService.getCryptoMarkets().pipe(take(1)).subscribe(res => {
let data = res.data;
for(let i = 0; i < 6; i++) {
top5CryptoIds.push(data[i].baseId)
}
this.top5Ids = top5CryptoIds;
});
}
}
【问题讨论】:
-
您订阅了一个可观察对象,因为它异步发出。 IE。在方法 getTop5Crypto() 返回很久之后。就像您发送电子邮件一样:您不能指望在发送电子邮件后立即从响应中提取数据。只有在电子邮件客户端通知您回复已返回时,您才能这样做。
-
@JBNizet 太好了。但是如何修复此代码?
-
例如,通过阅读您从 patjim 得到的答案。但最重要的是,暂时远离这段代码,阅读和练习异步 RxJS。