ionic2- 动态更改离子卡的内容



我有一个书籍列表,这些书籍通过后端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页面中显示更改

如果图书价格发生变化,此功能中将提供新价格,我想更新该图书的卡片信息

在网络上,它可以很容易地实现。不知道如何在离子中实现这一点。任何人都可以为我提供解决方案吗?

网页代码

<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

});
}
});
});
}
}

发布作为答案,因为我无法发表评论。但也许是因为范围发生了变化,请使用"=>"而不是"函数"。

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;
}
});

相关内容

  • 没有找到相关文章

最新更新