Search code examples
javascriptangulartimeoutdelayangular-universal

Angular 5 how to set minimal delay (or timeout)?


The code of request is simple:

getItem() {
    return this.http
        .post<ItemModel>(`${this.apiUrl}/${methodUrl}`, {})
        .subscribe(response => {
            ...
        });
}

There two cases depends on how long server will process the request: we reseive sersponse within less then 1 minute and within more then 1 minute.

I need to set minimum delay for 1 minute for first case when we reseive response fast, faster then within 1 minute.

But I can't simpli add delay in response => {} like this:

getItem() {
    return this.http
        .post<ItemModel>(`${this.apiUrl}/${methodUrl}`, {})
        .subscribe(response => {
            setTimeout(()=>{ ... }, timeoutValue)
            ...
        });
}

Because in this case the delay time summs with response time, for example if response 0.5 min and timeoutValue == 1 min, we will wait for 1.5 min. I need to set min total time 1 min somehow.

How do I set it?


Solution

  • You can use forkJoin

    getItem() {
     return this.http
         .post<ItemModel>(`${this.apiUrl}/${methodUrl}`, {})
         .subscribe(response => {
             ...
         });
    }
    
    
    getItemDelayed() {
        return forkJoin(
             getItem(),
             interval(1000).pipe(take(1))
        )
    }
    

    With this every observable will be executed in parallel, but result will be sent only when the two are completed.

    So if the request take less then one second, result will arrive in one second.