2017-06-14 101 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

为什么不使用'setInterval'呢? –

+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小号可能更适用。

使用rxinterval操作:

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

,但如何使用它来与我的代码中的外部方法交流? – ChristoK

+0

你必须暴露observable本身,没有任何包装。然后,任何人都可以订阅它。 – Hitmands

+0

但我怎么知道api调用是否成功或返回错误? – ChristoK