我从远程服务器获取数据。 CORS已配置。我使用interval()运算符形式RXJS库。
组件:
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);
}
)
};
服务返回可观察对象:
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);
};
}
但是在用户进入页面后,他等待5秒钟(并查看白色屏幕)。我需要在加载页面后立即发送请求。然后每5秒重复一次请求
答案 0 :(得分:2)
您可以使用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);
})
};