Can you tell me how to access a value from the async
setTimeout()
observable
method? I have written just normal async
method as below.But as we all know it doesn't do what I need.How can I use observable
here? Any guidance would be really appreciated.
page.ts
loader = this.loadingControllerService.dismissLoaderWhenNoInternet(loader);
provider.ts
dismissLoaderWhenNoInternet(loader: Loading): Loading {
setTimeout(() => {
if (loader) {
loader = null;
return loader;//not working here
}
}, 5000);
return loader;
}
To get return value from setTimeout with JavaScript, we can create a promise from the setTimeout code. const x = () => { const promise = new Promise((resolve, reject) => { window. setTimeout(() => { resolve("done!"); }); }); return promise; }; const y = async () => { const result = await x(); console. log(result); };
An ObservableValue is an entity that wraps a value and allows to observe the value for changes. In general this interface should not be implemented directly but one of its sub-interfaces ( ObservableBooleanValue etc.). The value of the ObservableValue can be requested with getValue() .
We can use the setTimeout() function for various reasons. It is best to allow Angular to run change detection once, between the actions that we would otherwise perform synchronously.
Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.
To deal with async in es6 you have 2 choices:
Promise: use for function just return once time:
asyncPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Hello");
}, 2000)
})
}
this.asyncPromise().then(data=>{console.log(data)}); //Print Hello after 2s
Observable: use for function return more than once time:
import { Observable } from 'rxjs/Observable';
asyncObservable() {
return new Observable(observer => {
setInterval(() => {
observer.next("Hi");
}, 1000)
})
}
this.asyncObservable().subscribe(data=>{console.log(data);}) //Print Hi every 1s
See more about differences between Promise and Observable
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