fipodas
fipodas

Reputation: 25

How to delay call function without setTimeout ? Angular

I need to delay call of function for few seconds. 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 ? 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.

I will try to explain once again:

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

Upvotes: 1

Views: 1463

Answers (1)

Radek Marčan
Radek Marčan

Reputation: 76

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).

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? Or is lastAddedItem API call?

Also I would suggest to set allData as private since don't want it to be called from teplate or another component.

Upvotes: 1

Related Questions