[英]Using Angular 2/RxJs 5 beta observable to stream data from a while loop
I want to create a simple app in Angular 2 which computes (for example) primes in a while loop and updates new found values to the view. 我想在Angular 2中创建一个简单的应用程序,该应用程序在while循环中计算(例如)质数并将新发现的值更新到视图中。 I want to display the primes array with *ngFor in a real time way so that the user sees that the app is computing.
我想用* ngFor实时显示primes数组,以便用户看到该应用程序正在计算。 The script is running in a web worker so the while loop shouldn't block the app.
该脚本在网络工作者中运行,因此while循环不应阻止该应用程序。 This is what i had in mind:
这就是我的想法:
// Prime Service
getPrimes(n: number) {
var i = 0;
while (1) {
this.isPrime(i) ? this._dataStore.primes.push(i) : null;
this.primes$.next(this._dataStore.primes);
i++;
}
}
Items are only pushed after all loops are finished tho (tested with for loop aswell). 仅在所有循环完成后才推送项目(还要测试for循环)。 I tried looking into using generators but that feature doesn't seem to work in RxJs 5 beta yet.
我尝试使用生成器,但该功能似乎在RxJs 5 beta中尚不起作用。
Is there a better solution or are observables not suited for what I want in general? 是否有更好的解决方案,或者可观察性不适合我的总体需求?
You could use the Observable.range() operator to generate the number sequence and then filter the sequence using your isPrime() method. 您可以使用Observable.range()运算符生成数字序列,然后使用isPrime()方法过滤该序列。
you could also use Observable.generate() . 您也可以使用Observable.generate() 。 but I think it's not supported by Angular yet.
但我认为Angular还不支持。
Here is a sample code (plunker) . 这是一个示例代码(插件) 。 you just need to change the isPrime() implementation and the range of the numbers.
您只需要更改isPrime()实现和数字范围即可。
import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'my-app',
template: `<h1>Count: {{primes.length}}</h1>
<div *ngFor="#prime of primes">{{prime}}</div>`
})
export class AppComponent {
primes:number[] = [];
ngOnInit(){
var source = Observable.range(2,1000);
source.filter(i => this.isPrime(i)).subscribe(i=>this.primes.push(i));
}
isPrime(num:number){
for(let n of this.primes)
if(num % n ===0) return false
return true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.