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:
Argument of type 'Promise' is not assignable to parameter of type 'OperatorFunction'. Type 'Promise' provides no match for the signature '(source: Observable): Observable'.
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));
Observables are "lazy", meaning if no one is listening, nothing happens.
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.
you can use delay function
public GetCurrentUserDelayedTest(): Observable<User>
{
return of(new User(""))
.pipe(delay(2000));
}
A more detailed example using HttpClient:
of(null).pipe(
delay(2000),
flatMap(() => {
return this.http.post<any>(url, params);
})
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With