Angular 2订阅陷入循环

时间:2017-03-26 17:33:52

标签: angular typescript angularfire subscribe

我从我的firebase数据库中获取了一条记录,并且我试图更新它的价值,但我的订阅方法正在做一些我不明白的事情。它看起来像无限循环。一些想法?

示例:

Multiple test1 values in array

代码:

组件方法:

borrowBook(isbn) {
   var uid;
   this.angularFireSubscriber = this.af.auth.subscribe(
      auth => {
        uid = auth.uid
     });
   this.bb.getBorrowedBooks(uid).subscribe(
      result => {
        var books = result[0].books;
        books.push('test1');
        this.bb.updateOrder(result[0].$key, books);
      }
   );
}

服务方法:

updateOrder(key, books) {
    this.af.database.list('borrowedBooks').update(key, { books: books});
}

getBorrowedBooks(uid: string) {
   return this.af.database.list('borrowedBooks',
      {
        query: {
          orderByChild: 'uid',
          equalTo: uid
        }
      }
   );
 }

度过美好的一天!

2 个答案:

答案 0 :(得分:0)

当您尝试在订阅函数内执行更新操作时,通常会出现此问题。 Observable类型是一种实用程序,可以异步或同步地将数据流传输到已订阅了Observable的各种组件或服务。

如果要使更新功能仅运行一次,则解决方案是设置一个计数器,否则它将无限运行。

例如声明一个计数器

 counter:number = 0

然后在您的代码中

borrowBook(isbn) {
 var uid;
  this.angularFireSubscriber = this.af.auth.subscribe(
   auth => {
     uid = auth.uid
   });
 this.bb.getBorrowedBooks(uid).subscribe(
  result => {
    var books = result[0].books;
    books.push('test1');
     //check the counter here
     if(counter ==0){ 
       this.bb.updateOrder(result[0].$key, books); 
      }   
      this.counter++
   }
 );
}

答案 1 :(得分:0)

在@FelixRunye提到的内容之外,可以通过使用如下所示的rxjs来做得更好

borrowBook(isbn) {
let isAlive = true;
 var uid;
  this.angularFireSubscriber = this.af.auth
.subscribe(
   auth => {
     uid = auth.uid
   });
 this.bb.getBorrowedBooks(uid)
.pipe(
takeWhile(() => isAlive)
)
.subscribe(
  result => {
    isAlive = false;
    var books = result[0].books;
    books.push('test1');
    this.bb.updateOrder(result[0].$key, books);  
   }
 );
}

这还将确保每次借阅Book时,所有借书的逻辑仅有效运行一次