2017-06-14 15 views
1

1分毎に約束を返す方法はありますか? 私はこのような何かをしようとしていたが、それは最初に一度だけの約束を返します。1分ごとに約束を返しますか?

startWork() { 

    this.dataService.startPing(details).then((result) => { 
     this.timeSlotsRefresh(); 
    }, (err) => { 
     console.log(err); 
    }); 
    } 

、その後:

startPing() { 
let startingTime = new Date(); 

return new Promise((resolve, reject) => { 

    let source = Rx.Observable.timer(startingTime, 60000).timeInterval().pluck('interval'); 


    this.Subscription = source 
    .subscribe(data => { 

      this.http.post('http://localhost:63203/api/Ping', JSON.stringify(this.offlinePings[i])) 
      .map(res => res.json()) 
      .subscribe(data => { 
       resolve(data); 
      }, (err) => { 
       reject(err); 
      }); 
    }); 
}); 

}

それは基本的にこの機能を1分ごとに通知しなければなりませんthis.timeSlotsRefresh();を呼び出してデータをリフレッシュするには、どうすればいいですか?

+6

intervalオペレータとrxを使用して

? –

+0

あなたは私にそれの例を教えてくれますか? – ChristoK

+0

https://stackoverflow.com/questions/35592716/making-polling-request-in-angular-2-using-observable –

答えて

2

@Injectable 
 
class Ping { 
 
    readonly observable = Rx.Observable.interval(60000); 
 
    
 
    subscribe(...cbs) { 
 
    return this.observable.subscribe(...cbs); 
 
    } 
 
} 
 

 

 
@Component 
 
class Foo implements OnInit, onDestroy { 
 
    private subscription = null; 
 
    
 
    constructor(private ping: Ping) {} 
 
    
 
    onPing(count) {} 
 
    onPingError(error) {} 
 
    onPingFinish() {} 
 
    
 
    ngOnInit() { 
 
    this.subscription = this.ping.subscribe(
 
     (...d) => this.onPing(...d), 
 
     (...e) => this.onPingError(...e), 
 
     (...f) => this.onPingFinish(...f) 
 
    ); 
 
    } 
 
    
 
    ngOnDestroy() { 
 
    this.subscription.unsubscribe() 
 
    } 
 
}

Promise sは一度だけ動作するように意図されている、あなたはより良い合うことができストリーミングとObservable Sのようなもののために必要があるかもしれません。代わりに、 `setInterval`を使用しないのはなぜ

var source = Rx 
 
    .Observable 
 
    .interval(2000 /* ms */) 
 
    .map(id => fetch(`https:\/\/jsonplaceholder.typicode.com\/posts\/${id}`).then(res => res.json())) 
 
; 
 

 
var subscription = source 
 
    .subscribe(post => console.log('New Post', post)) 
 
;
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.js"></script>

+0

しかし、私のコードのような外部メソッドとcomunicateにそれを使用する方法? – ChristoK

+0

ラッパーなしでobservable自体を公開する必要があります。それで誰もそれを購読することができます。 – Hitmands

+0

しかし、api呼び出しが成功したか、エラーを返したかどうかはどうすればわかりますか? – ChristoK

関連する問題