2016-12-14 88 views
1

此函数记录用户读取页面并在用户点击下一页时触发。检查数组中是否有任何项目等于此值

它首创订阅到数据库,检索所有用户已经阅读网页的清单..

我的目标是只记录页面,用户尚未读取例如不在数据库中。

如果从数据库返回的列表包含与刚才读取的页面相同的页码,则此函数不会将页面记录为正在读取。

但是在第一次点击这只作品,然后,如果我回到同一页面再次,然后单击下一步它会记录的页码到数据库...

如何修复这个bug任何建议,需要再次注意这个代码我知道它简单的事情..干杯!

logAsWatched() { 
let uid = this.windowRef.nativeWindow.firebase.auth().currentUser.uid; 
this.projectId = this.uidpage.project.id; 
this.subscription = this.af.database.list(`pagelogs/${uid}/${this.projectId}`).subscribe(
    data => { 
    console.dir(data); 
    if (data.length >= 1) { 
     let pagelogArray = []; 
     for (let i = 0; i < data.length; ++i) { 
     let pageNumber = data[i]; 
     pagelogArray.push(pageNumber); 
     } 
     console.log('pagelogArray', pagelogArray); 
     console.log('page order', this.pageOrder); 

     let newArray = []; 

     for (let i = 0; i < pagelogArray.length; ++i) { 
     newArray.push(pagelogArray[i].pNumber); 
     } 
     console.log(`newArray : ${newArray}`); 
     if (!newArray.indexOf(this.pageOrder)) { 
     console.log('page has allready been logged'); 
     } else { 
     console.log('logging this page as watched'); 
     this.setLogAsWatchedData(); 
     } 
    } else { 
     console.log('No page logs have been added'); 
     this.setLogAsWatchedData(); 
    } 
    }, (error) => { console.log(`page log error: ${error}`); } 
); 

}

setLogAsWatchedData() { 
    this.subscription.unsubscribe(); 
    let uid = this.windowRef.nativeWindow.firebase.auth().currentUser.uid; 
    this.windowRef.nativeWindow 
     .firebase.database(). 
     ref(`pagelogs/${uid}/${this.projectId}`) 
     .push().set({ pNumber: this.pageOrder }); 

    } 
+0

您错误地检查了页面被记录:'if(!newArray.indexOf(this.pageOrder))'。它应该是'if(newArray.indexOf(this.pageOrder)!== -1)' –

回答

1

我想你可以看看如何使用过滤器[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter],到了页面为已读VS无法读取记录。

+0

感谢那@Ryan Basmajian!但是该错误仍在代码中。 这很奇怪,因为只有2点数据将被发送到服务器,这是在console.log的两个if else语句的末尾。 '} else { console.log('将此页面记录为已观看'); this.setLogAsWatchedData(); } }其他{ console.log('没有页面日志已被添加'); this.setLogAsWatchedData(); ' 奇怪的是,第二次console.log没有显示在控制台上时,页面被记录下来...... – Dave

+0

结束了重构代码以使用promise来返回数据而不是订阅它。这已经解决了数据第二次被记录的问题。干杯! – Dave

相关问题