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