javascript-订阅功能导致循环
作者:互联网
我正在尝试使用cryptocompar的API来获取数据.
更新了更多详细信息,并从代码中删除了ngClass.
在test.ts中
// data from library page
coinsGroup = [];
datainfo: Observable<any>;
coins:any;
constructor(public navCtrl: NavController, public navParams: NavParams, public http: HttpClient)
{
}
ionViewDidLoad()
{
console.log('ionViewDidLoad TestPage');
this.coinsGroup = this.navParams.data;
}
getdetail(coin) {
this.datainfo = this.http.get("https://min-api.cryptocompare.com/data/pricemultifull?fsyms="+coin+"&tsyms=USD");
this.datainfo.map(res => res)
.subscribe(data => {
this.coins = data['DISPLAY'][coin]['USD']['PRICE']
console.log('my data: ', this.coins);
});
}
在test.html上
<span *ngIf="coinsGroup.symbol" class="bold1">
{{getDetail(coinsGroup.symbol)}}</span>
coinGroup将从库页面中获取符号,例如[‘BTC’,’ETH’,.. etc]
在chrom控制台上,它一直循环播放,如下所示,直到浏览器崩溃为止.
与地图一起使用subscribe()时,会导致无休止的循环,如上所示,不确定为什么,以及如何解决此问题?
解决方法:
是.
< span [ngClass] =“ getdetail('BTC')” class =“ bold1”> {{硬币}}< / span>
是问题. ngClass尝试为该类设置字符串值. (因此您可以应用css).这不是您要尝试的操作,而是要检索所有硬币然后显示它们.
这样做的方法是这样的:
datainfo: Observable<any>;
coins:any;
constructor(public navCtrl: NavController, public navParams: NavParams, public http: HttpClient)
{}
// load the coins after the view is loaded, can also be done on ngOnInit
ionViewDidLoad(){
this.getDetail('BTC');
}
getdetail(coin) {
this.datainfo = this.http.get("https://min-api.cryptocompare.com/data/pricemultifull?fsyms="+coin+"&tsyms=USD");
this.datainfo
.map(res=>res)
.subscribe(data => {
this.coins = data
console.log('my data: ', this.coins);
});
}
并简单地设置
<ion-content padding>
<div style="text-align: center;">
<!-- the ngIf directive will only show this span if `coins` is defined -->
<span *ngIf="coins" class="bold1">{{ coins }}</span>
</div>
</ion-content>
如果要创建更多硬币,最佳实践可能如下:
let coinList = ["BTC", "ETH", "LTE"];
constructor(/* ... */) {}
getDetail(coin): Observable<any> {
// don't subscribe, return Observable
this.http.get("...").map(res=>res);
}
并在您的html中
<ion-content padding>
<div style="text-align: center;">
<span *ngFor="let coin of coinList" class="bold1">
{{ getDetail(coin) | async }}
</span>
</div>
</ion-content>
标签:angular,typescript,ionic3,javascript 来源: https://codeday.me/bug/20191025/1926450.html