![](/img/trans.png)
[英]Get value of Observable or value of BehaviourSubject Angular2
[英]Periodically updating Observable value in Angular2
我想每5秒點擊一次並顯示一次來自http鏈接的內容,看來是使用angular2,可觀察的方式將成為解決方案?
getPhaseVotes(issue: string) {
return this.http.get(this.URL + 'issue/' + issue + '/getPhaseVotes')
.subscribe(data => this.phase_votes = data.json(),
err => console.log(err),
() => this.getStatus(issue));
}
我應該如何每5秒更新一次?
您可以使用Observable
的interval
運算符:
@Injeactable()
export class SomeService {
constructor(private http:Http) {}
getPhaseVotes(issue: string) {
return Observable.interval(5000).flatMap(() => {
return this.http.get(this.URL + 'issue/' + issue + '/getPhaseVotes')
.map(res => res.json());
});
}
}
這樣,您需要調用一次getPhaseVotes
方法並對其進行訂閱。 每隔5秒,將透明執行一次HTTP請求,並在訂閱的回調中提供結果:
@Component({
(...)
})
export class SomeComponent {
constructor(private service:SomeService) {
this.service.getPhaseVotes('someissue')
.subscribe(data => this.phase_votes = data,
err => console.log(err),
() => this.getStatus(issue));
}
}
本文可能會在“投票”部分為您提供更多提示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.