简体   繁体   English

如何在没有setTimeout的情况下延迟调用function? Angular

[英]How to delay call function without setTimeout ? Angular

I need to delay call of function for few seconds.我需要将 function 的呼叫延迟几秒钟。 I have solution which work but enough good.我有有效但足够好的解决方案。

  public recieveNewContact() {
      this.allData();
      setTimeout(() => {  
         this.lastAddedItem()
      }, 100)
  }


  public ngOnInit() { 
    this.allData()
  }

  allData() {
      this.accountsService.getContactPerson().subscribe(
         (data) => {
             console.log(data)
        }
      )
    }

This is work good but i don't like this... I need better solution maybe with rxjs?这很好用,但我不喜欢这样......我可能需要更好的解决方案 rxjs? Delay?延迟?

which is very important.这是非常重要的。

In this case, I don't need this:在这种情况下,我不需要这个:

  allData() {
      this.accountsService.getContactPerson().subscribe(
         (data) => {
             console.log(data)
             this.lastAddedItem()
        }
      )
    }

Because i wan't to load lastAddedItem() on init.... Only when is recieveNewContact triggered.因为我不想在初始化时加载 lastAddedItem() ....只有当 recieveNewContact 被触发时。

I will try to explain once again:我将尝试再次解释:

  public recieveNewContact() {
      this.allData(); 
      this.lastAddedItem()// here to be called when is allData finished without setTimeout
  }

I would suggest to use either delay (if you are 100% sure of the completation time) or finalize (if you want to be sure it will wait no matter how long it takes) (rxjs).我建议使用delay (如果你 100% 确定完成时间)或finalize (如果你想确保无论需要多长时间它都会等待)(rxjs)。

Is it necessary to call allData function everytime since you can keep local copy of data in variable and then do the adjustment on it?是否需要每次都调用 allData function,因为您可以将数据的本地副本保存在变量中,然后对其进行调整? Or is lastAddedItem API call?或者是 lastAddedItem API 调用?

Also I would suggest to set allData as private since don't want it to be called from teplate or another component.此外,我建议将 allData 设置为私有,因为不希望从 teplate 或其他组件调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM