Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a value from setTimeout Observable method

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;
  }
like image 543
Sampath Avatar asked Jul 24 '17 03:07

Sampath


People also ask

How do I return a value from setTimeout?

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); };

What is observable value?

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

Can we use setTimeout in Angular?

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.

What are observable methods?

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.


1 Answers

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

like image 54
Duannx Avatar answered Sep 22 '22 16:09

Duannx