[英]How get data from server? Use interval operator
I get data from remote server. 我从远程服务器获取数据。 CORS is configured. 已配置CORS。 I use interval() operator form RXJS library. 我使用RXJS库的interval()运算符。
Component: 零件:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/switchMap';
private getUserTasks(userId): void {
Observable
.interval(5000)
.switchMap(() => this.tasksService.getUserTasks(userId))
.subscribe(
data => {
this.userTasks = JSON.parse(data);
console.log('userTasks', this.userTasks);
}
)
};
Service return observable object: 服务返回的可观察对象:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TasksService {
constructor(private http: HttpClient) { };
getUserTasks(userId): Observable<any> {
return this.http.get('http://blabla.com/app_tasks/user_tasks?user_id=' + userId);
};
}
But after the user enters the page, he waits 5 seconds (and looks at the white screen). 但是,当用户进入页面后,他等待5秒钟(并看着白屏)。 I need to send a request immediately after the page is loaded. 页面加载后,我需要立即发送请求。 And then every 5 seconds the request was repeated 然后每5秒重复一次请求
You can use startWith to have the sequence emit an initial value 您可以使用startWith使序列发出初始值
private getUserTasks(userId): void {
Observable
.interval(5000)
.startWith(0)
.switchMap(() => this.tasksService.getUserTasks(userId))
.subscribe(data => {
this.userTasks = JSON.parse(data);
console.log('userTasks', this.userTasks);
})
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.