我在投票服务中遇到这种情况。
在每次民意测验中,我都会将记录插入一个数组(this.status)中并返回该数组。
但是每次迭代我都需要清除数组并开始一个新的数组怎么做?
请在下面找到代码:
pollUsecases(userId,interval):any[] {
// Polling in every 1 min
Observable.interval(interval).startWith(0)
.switchMap(() => this.http.get<any[]>(Appconfig.HISURL+ '/api/UsecaseExecution/GetUsecaselist/1/' + userId +'/100000/1')).map(data => data)
.subscribe((data) => {
data.forEach((element, index) => {
// Observable.timer(0, 1000) Immediatly execute the api without any dealy
Observable.timer(0, 1000)
.switchMap(() => this.http.get<any[]>(Appconfig.HISURL+ '/api/UsecaseExecution/GetUsecaseExecutionStatus/' + element.UsecaseId)).map(data => data)
.subscribe((data) => {
this.status[index]=data;
});
});
});
return this.status;
}
答案 0 :(得分:0)
这里是我的版本,每个步骤或操作员都带有注释,以解释原因
// Polling in every min
const ONE_MINS = 1000 * 60;
return Observable.interval(ONE_MINS) // emit every minute, return the Observable
.mergeMap(() =>
this.http.get<any[]>(
Appconfig.HISURL + '/api/UsecaseExecution/GetUsecaselist/1/' + userId + '/100000/1',
),
)
.mergeMap((data) => from(data)) // assume data is array, use from operator to transform array to event stream
.mergeMap((element) => this.http.get<any[]>( // each element in stream mergeMap to a request observable
Appconfig.HISURL +
'/api/UsecaseExecution/GetUsecaseExecutionStatus/' +
element.UsecaseId)
.toArray() // finally, collect all request and transform to an array
// in another module or file call the function to get Observable
// const ob$ = getObservable();
// subscribe and you'll get array here
ob$.subscribe((arr) => this.arr = arr);