【发布时间】:2017-12-08 11:55:55
【问题描述】:
在我的应用程序中,我有一个搜索栏和下面的“标签”列表。它用于让用户添加一个新标签,带有一个控制过滤器来检查他输入的单词是否已经存在于列表中。仅当新标签不存在时才会将其添加到数据库中。
如果可以添加单词,则可以看到一个按钮,单击它后,新单词会被推送到数据库中。我期望的行为是,添加单词后,搜索栏下方的列表会实时更新为新单词;相反,添加后它变为空白,我必须返回然后再次进入该页面才能看到新列表。
下面是搜索栏+列表的html代码:
<ion-searchbar (ionInput)="getItems($event)" placeholder="Add tag ... "></ion-searchbar>
<ion-scroll style="width:100%;height:60vh" scrollY="true">
<ion-list>
<ion-item *ngFor="let tag of tagList">
<h2> {{ tag.nome }} </h2>
</ion-item>
</ion-list>
</ion-scroll>
<button ion-button [disabled]="!isEnabled"(click)="clickedButton()">Add</button>
在 .ts 文件中,这是我用来保存标签和刷新列表的代码:
export class NewtagPage {
public tagList: Array<any>;
public loadedTagList: Array<any>;
constructor(public navCtrl: NavController, public navParams: NavParams, public api: Api,
public menuCtrl: MenuController, public toastCtrl: ToastController) {
var ref1 = firebase.database().ref('/tag/'); //get the tags from DB
//creo la lista di tag
ref1.once('value', tagList => {
let tags = [];
tagList.forEach( poi => {
tags.push(poi.val());
return false;
});
this.tagList = tags;
this.loadedTagList = tags;
});
}
ionViewWillEnter() {
this.initializeItems();
}
refreshItems():void{
var ref1 = firebase.database().ref('/tag/');
ref1.once('value', tagList => {
let tags = [];
tagList.forEach( poi => {
tags.push(poi.val());
return false;
});
this.tagList = tags;
this.loadedTagList = tags;
});
}
initializeItems(): void {
this.tagList = this.loadedTagList;
}
presentToastOk(){
let toast = this.toastCtrl.create({
message: 'Tag was added!',
duration: 2000,
position: 'top'
}).present();
this.initializeItems();
}
clickedButton(){
if (this.tagList.length==0){//posso aggiungere il tag
var tagData = {
nome: this.textSearch
}
var key = firebase.database().ref().child('tag').push().key;
var updates = {};
updates['/tag/'+key] = tagData;
updates['/point_of_interest/'+ this.poi.chiave + '/tags/' + key] = "true";
firebase.database().ref().update(updates);
this.presentToastOk();
this.refreshItems();
this.isEnabled = false;
} else {
this.presentToastWrong();
}
}
//filter function
getItems(searchbar) {
// Reset items back to all of the items
this.initializeItems();
// set q to the value of the searchbar
var q = searchbar.srcElement.value;
this.textSearch = q;
// if the value is an empty string don't filter the items
if (!q) {
return;
}
this.tagList = this.tagList.filter((v) => {
if(v.nome && q) {
if (v.nome.toLowerCase().indexOf(q.toLowerCase()) > -1) {
return true;
}
return false;
}
});
if (this.tagList.length==0){
this.isEnabled = true;
} else{
this.isEnabled = false;
}
}
}
过滤器功能完美,我只是为了完整性添加了它。
如您所见,我在创建页面时做的第一件事是获取 firebase 的标签列表。然后,当单击按钮时,将标签添加到数据库中,通过“presentToastOk”函数重新初始化项目,然后刷新代表要在html上显示的列表的变量。
当我添加一个新单词时,列表会重新出现片刻,然后立即消失。
我在另一个项目中使用了相同的方法并且工作正常。为什么它不再工作了?我照原样复制粘贴代码,现在找不到问题。
【问题讨论】:
标签: angular firebase ionic-framework