我有一个从后端API通过提供程序提取到课程的书籍列表。这是我得到的样本数据
{
"success":true,
"books":[
{
"id":1000,
"book_code":"CC219102",
"read_status":"completed",
"name":"Book A",
"price":"80"
},
{
"id":1001,
"book_code":"CC219103",
"read_status":"reading",
"name":"Book B",
"price":"50"
},
{
"id":1002,
"book_code":"CC219104",
"read_status":"completed",
"name":"Book C",
"price":"120"
},
{
"id":1003,
"book_code":"CC219105",
"read_status":"yet_to_read",
"name":"Book D",
"price":"75"
},
{
"id":1004,
"book_code":"CC219106",
"read_status":"completed",
"name":"Book E",
"price":"100"
}
]
}
正如您所看到的,在这种情况下,API会重新调整五本书。我在控制器内部调用一个函数loadBooks()来获取这些数据并将它存储在一个数组中myBooks:any = [];
我迭代这个数组并使用离子卡显示每本书。
事情是,我们获得的数据可能会发生变化。还有另一个函数refreshBookData()再次获取数据,这是使用套接字实现的。因此,当有更改时,我也想在html页面中显示更改
如果图书价格发生变化,此功能将提供新价格,我想更新该图书的卡片信息
在网络中,它可以轻松实现。不知道离子是如何实现的。任何人都可以为我提供解决方案吗?
HTML CODE
<ion-card *ngFor="let book of books" id="{{book.book_code}}">
<ion-grid>
<ion-row class="{{book.read_status}} row">
<ion-col>
<span>{{book.name | uppercase}}</span>
</ion-col>
<ion-col>
<div>
<div float-right>{{book.price}}</div>
</div>
</ion-col>
</ion-row>
</ion-grid>
</ion-card>
组件类看起来像这样:
import { Component } from '@angular/core';
import { NavController, NavParams, LoadingController } from 'ionic-angular';
import * as io from "socket.io-client";
import { BookServicesProvider } from './../../providers/book-services/book-services';
import { Storage } from '@ionic/storage';
@Component({
selector: 'page-my-books-page',
templateUrl: 'my-books-page.html',
})
export class MyJobsPage {
memberId: any= 1;
myBooks: any = [];
constructor(public navCtrl: NavController, public navParams: NavParams,
private storage: Storage, private bookService: BookServicesProvider) {
this.loadBooks(this.memberId);
this.refreshBookData(this.memberId);
}
loadBooks(memberId) {
let reqParams = {
memberId: memberId
};
this.jobService.myJobs(reqParams)
.then(data => {
this.myJobs = data['jobs'];
});
}
refreshBookData(memberId) {
var params = {
memberId: memberId.toString()
};
var socket = io('localhost:3000/books');
socket.on('connect', function (obj) {
//Emitting the params to socket
socket.emit('bookStatuses', params);
socket.on('book_statuses', function (data) {
//received data; storing it in temp variable
var myBooksTemp = data.books;
if (myBooksTemp) {
//iterating through the changed data
myBooksTemp.forEach((value, key, index) => {
//code to change html here
});
}
});
});
}
}
答案 0 :(得分:0)
发帖作为答案,因为我无法发表评论。但也许是因为范围在变化,使用&#39; =&gt;&#39;而不是&#39;功能&#39;。
socket.on('book_statuses', data => {
//received data; storing it in temp variable
var myBooksTemp = data.books;
if (myBooksTemp) {
//If I understood right, here is where you get the updated
//books, so, set in 'myBooks'
this.myBooks = myBooksTemp;
}
});