【发布时间】:2018-10-01 09:51:18
【问题描述】:
我正在尝试创建一个表单来提交详细信息,但是当我订阅服务时,订阅完成了两次。首先是空数据,其次是实际数据。
组件.ts
addBook() {
this.errorMessage = null;
this.fireService.getBook(this.bookDetails.isbn).subscribe(data => {
console.log('subscribe called');
if (null != data) {
this.dbox.open(DialogBoxComponent, {
data: { title: 'Error', content: 'Book is already present in Library. Select Edit book to modify the details', button: false }
});
this.errorMessage = 'Book is already present in Library. Select Edit book to modify the details';
} else {
this.fireService.addBook(this.bookDetails);
this.dbox.open(DialogBoxComponent, {
data: { title: 'Success', content: 'Book has been Added to Database', button: false }
});
this.router.navigateByUrl('/add-book');
}
});
}
服务.ts
getBook(id) {
console.log('called firebase get book');
return this.db.doc(`/books/${id}`).valueChanges();
}
下面是来自 chrome 控制台的图像。这表明订阅被调用了两次,而不是 firebase 服务。
Chrome console logs: Image please click to view
chrome 控制台日志
called firebase get book
subscribe called
subscribe called
请帮忙
【问题讨论】:
-
试试
this.fireService.getBook(this.bookDetails.isbn).pipe(filter(data => !!data)).subscribe(...) -
@ChauTran 尝试了您的建议,我收到错误提示“void”类型的“this”上下文不可分配给“Observable”类型的方法的“this”。
-
可能是因为我使用的是
pipable methods。对不起,忘了问你正在运行什么版本的 angular/rxjs。运行.filter(data => !!data)的行为方式也应该相同;)
标签: javascript angular typescript firebase angular5