Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay an observable in Angular 6 / Typescript

I have the following method GetCurrentUserDelayedTest that i wanted to put a delay on. I have left the original implementation here GetCurrentUser to demonstrate how i was originally using it:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { User } from '../models/user';

export class UserService {

    // Normal method without delay
    public GetCurrentUser(): Observable<User>
    {
        return of(new User(""));
    }

    // Method with delay attempt at code
    public GetCurrentUserDelayedTest(): Observable<User>
    {
        var observable = new Observable<User>((observable) => {
            setTimeout(() => {
                return observable.complete();
            }, 2000);
        });

        observable.subscribe(() => {
            return of(new User(""));
        });

        return observable;
    }
}

I'm trying to delay the method from returning its data by 2 seconds.

What am i doing wrong? I'm brand new to angular 6 and typescript.

I'm calling it like this:

this.userService.GetCurrentUserDelayedTest()
    .subscribe((currentUser) => {
        this.loadingGameState = false;
    });

The "Loading App" part remains on screen (no errors are thrown) rather than updating the view to show "Welcome"

<div *ngIf="loadingGameState">Loading App</div>
<div *ngIf="!loadingGameState">
  Welcome
</div>

Edit:

enter image description here

Argument of type 'Promise' is not assignable to parameter of type 'OperatorFunction'. Type 'Promise' provides no match for the signature '(source: Observable): Observable'.

like image 790
Jimmyt1988 Avatar asked Jun 10 '18 22:06

Jimmyt1988


People also ask

How do I add a delay in TypeScript?

How do I create a delay in TypeScript? You have to wait for TypeScript 2.0 with async / await for ES5 support as it now supported only for TS to ES6 compilation. await delay(1000); BTW, you can await on PromisePromiseIn other cases a future and a promise are created together and associated with each other: the future is the value, the promise is the function that sets the value – essentially the return value (future) of an asynchronous function (promise).https://en.wikipedia.org › wiki › Futures_and_promisesFutures and promises - Wikipedia directly: await new Promise(f => setTimeout(f, 1000));

Is observable lazy?

Observables are "lazy", meaning if no one is listening, nothing happens.

How do you use delayWhen?

delayWhen operator works in the following way: Subscribe to a source observable. When a new value arrives from a source observable, execute the callback function to get the duration observable corresponding to this value. Add the value and the corresponding duration observable to internal cache.


3 Answers

you can use delay function

public GetCurrentUserDelayedTest(): Observable<User>
{
    return of(new User(""))
       .pipe(delay(2000));
}
like image 78
izmaylovdev Avatar answered Nov 13 '22 23:11

izmaylovdev


A more detailed example using HttpClient:

of(null).pipe(
  delay(2000),
  flatMap(() => {
    return this.http.post<any>(url, params);
  })
);
like image 4
Ilya Scharrenbroich Avatar answered Nov 14 '22 00:11

Ilya Scharrenbroich


https://stackblitz.com/edit/angular-mznw5m?file=src%2Fapp%2Fuser.service.ts

Use in the declaration of the Observable observable.next() so you can trigger the subscribers.

like image 2
Bogdan Bogdanov Avatar answered Nov 13 '22 23:11

Bogdan Bogdanov