我正在使用离子3。我在更新库存数据时遇到问题。我可以经常在我的组件上获得更新,我可以在我的控制台中看到有关更改的信息,但不更新我的视图中的更改。但我的观点得到更新很少的情况。如果组件中发生 10 次更新意味着 1 次更新进入我的视野。我编写了如下代码,服务:
@Injectable()
export class MarketService{
fncallback:any;
stocks: string[][];
constructor( ) {
this.initStocks();
this.subscribeStocks();
}
subscribeStocks() {
this.lsClient = new LightstreamerClient("http://localhost:8080", "WBSTOCKLIST_REMOTE");
this.lsClient.connectionSharing.enableSharing("WBCommonConnection", "ATTACH", "CREATE");
this.lsClient.connect();
this.subscription = new Subscription("MERGE", this.itemNames, this.fieldNames);
this.subscription.setDataAdapter("WBQUOTE_ADAPTER");
this.subscription.addListener({
onItemUpdate: (updateObject) => {
var itemName = updateObject.getItemName();
updateObject.forEachChangedField((fieldName, fieldPos, val) => {
var itemIndex = this.itemNames.indexOf(itemName);
var fieldIndex = this.fieldNames.indexOf(fieldName);
console.assert(fieldIndex != -1);
console.assert(itemIndex != -1);
this.stocks[itemName][fieldName] = val;
});
this.fncallback(this.stocks);
}
});
this.lsClient.subscribe(this.subscription);
}
setcallback(fn){
this.fncallback = fn;
}
}
我的组件代码如下所示,
export class MarketPage {
baserates:any;
constructor(public marketService: MarketService) {
}
ionViewDidLoad() {
console.log( 'ionViewDidLoad MatketPage' );
this.marketService.setcallback((data)=>{
this.baserates = data;
console.log(this.baserates); //This update happens frequently
});
}
}
我的观点是这样的,
<ion-row class="light-border-btm align-items" *ngIf="baserates">
<ion-col col-3>Gold</ion-col>
<ion-col col-3>{{ baserates['SPOT-GOLD']['bid'] }}</ion-col>
<ion-col col-3>{{ baserates['SPOT-GOLD']['ask'] }}</ion-col>
<ion-col col-3>H:{{ baserates['SPOT-GOLD']['high'] }}<br/>L:{{ baserates['SPOT-GOLD']['low'] }}</ion-col>
</ion-row>
但我的观点没有经常更新,因为在组件基准率字段中获取更新。你能帮助任何人吗?我已经使用Lightstreamer来提高更新率。
您可以使用 ChangeDetectorRef 更新 UI。
在构造函数中收到来自 API 的响应后,添加依赖项
constructor(private cd: ChangeDetectorRef) {}
然后一旦你收到回复,只需打电话
this.cd.markForCheck((;