簡體   English   中英

如何在angular2中觀察到間隔后更新值?

[英]How to make observable in angular2 which updates value after interval?

我正在angular2中創建可觀察的。

我想創建一個可觀察值,它將在2秒后更新值。 到目前為止,我已經創建了這樣的東西。

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/observable';
import 'rxjs/Rx';
@Component({
  moduleId: module.id,
  selector: 'observable-demo',
  templateUrl: 'observabe-demo.component.html',
})
export class ObservabeDemoComponent implements OnInit {
   public data:any;
   public num:number;
   constructor() {

   //I want to update this observable value with fibonacci series after 2 seconds each.
   this.data=new Observable<any>(observer=>{
      setTimeout(()=>{
         observer.next(32);  
      },2000);          
   });

   let subscriber=this.data.subscribe(
      value=>this.num=value,
      err=>console.log(err),
      ()=>console.log("Completed")
     );
   } 

}

目前,2秒鍾后,我的觀察值將值更新為32。

但我想重復運行此函數,直到值達到10000。

我想以這種可觀察的方式存儲斐波那契數列並將其打印出來。

Angular2 Observables這樣的事情有可能嗎?

謝謝。

您可以在Observables上使用interval()函數:

return Observable
        .interval(2000) // time in ms
        .flatMap(() => {
            return nextNumber()
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM