从setTimeout Observable方法访问一个值

时间:2017-07-24 03:15:07

标签: angular typescript rxjs observable ionic3

您能告诉我如何通过async setTimeout() observable方法访问值吗?我已经编写了正常的async方法,如下所示。但是我们都知道它不能满足我的需要。我如何在这里使用observable?任何指导都会非常感激。

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

1 个答案:

答案 0 :(得分:6)

要在es6中处理异步,你有两个选择:
承诺:用于函数只返回一次:<​​/ p>

asyncPromise() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("Hello");
      }, 2000)
    })
}

this.asyncPromise().then(data=>{console.log(data)}); //Print Hello after 2s

可观察:用于函数返回多次:

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

详细了解differences between Promise and Observable