【问题标题】:Angular typescript subscribing to a variable does not give correct results订阅变量的角度打字稿不会给出正确的结果
【发布时间】: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


【解决方案1】:

this.booksService.getBookByName() 是异步的,它需要一些时间来执行,同时代码会继续执行。 checkBookExistenance应该返回一个 observable:

checkPreferenceExistenance(): Observable<boolean> {
    return this.booksService.getBookByName(bookNameName: trim(this.bookName)).pipe(
      first(),
      map(data => {
        if (data.length){
          return true;
        }else{
          return false;
        }
        })
// or shortform without if/else: map(data => data.length)
    );
  }

然后:

    this.checkPreferenceExistenance().subscribe(
      exist => {
        if (exist) {
          this.isError = true
          this.errorMessage = "The provided book name is already exists."
        } else {
          this.bsModalRef.hide()
        }
      }
    );

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2021-10-20
    • 1970-01-01
    • 2021-09-02
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2019-04-07
    相关资源
    最近更新 更多