【发布时间】:2022-01-18 06:37:48
【问题描述】:
Motive:我正在保存期间对书名进行验证 - 如果数据库中已经有同名的书,则应抛出验证错误消息。 如果用户输入的书名存在任何书籍,我的服务中有一个方法返回书籍对象。
调用此服务方法后,我订阅它,将结果分配给 bool 变量并检查 if 语句中的 bool 变量。由于使用 subscribe/observable,if 语句首先执行,然后调用订阅者,并且不会返回正确的值,也不会触发验证。
我哪里错了?提前致谢。
下面是我的代码:
export class AddBooksComponent implements OnInit{
bookName = "";
isError = false;
errorMessage="";
isPresent:boolean = false;
constructor(public bsModalRef: BsModalRef,private booksService: BooksService) { }
ngOnInit(): void { }
saveBooks() {
if(this.checkBookExistenance()) {
this.isError = true
this.errorMessage="The provided book name is already exists."
} else {
this.bsModalRef.hide()
}
}
checkPreferenceExistenance():boolean {
this.booksService.getBookByName(bookNameName:trim(this.bookName))
.pipe(first())
.subscribe((data) => {
// if the response has data then the book is present
if(data.length) {
isPresent= true;
}
else{
isPresent= false;
}
});
return isPresent;
}
}
【问题讨论】:
-
抛开对 async 语句的明显误解,
ngOnInit中的函数名称是this.checkBookExistenance(),但显示的函数是checkPreferenceExistenance()。这是笔误吗?
标签: javascript angular typescript observable subscribe