无法将promises数组转换为observable

时间:2018-04-08 03:24:17

标签: javascript angular rxjs observable angular5

修改 添加了Plunker:https://plnkr.co/edit/oiSHJxomTILEFLWUC0Y5

当我尝试使用concatAll通过按顺序连接内部Observable将高阶Observable转换为一阶Observable时,我遇到以下错误。

错误:

ERROR TypeError: Observable_1.Observable.from(...).concatAll is not a function

service.ts:

import 'rxjs/add/observable/fromEvent';
import { Observable } from 'rxjs/Observable';
import { WebWorkerService } from 'angular2-web-worker';


constructor(private _webWorkerService: WebWorkerService) {}


public computeFactorials(firstFactorial: number, numberOfFactorials: number): Observable < number > {
    let promises: Promise < number > [] = [];
    for (let i = firstFactorial; i < firstFactorial + numberOfFactorials; i++) {
        const p: Promise < number > = this._webWorkerService.run(this.fact, i);
        promises.push(p);
    }

    return Observable.from(promises.map((promise) => {
        return Observable.from(promise);
    })).concatAll();
}

public fact(x) {
    try {
        if (x == 0) {
            return 1;
        }
        if (x < 0) {
            return undefined;
        }
        for (var i = x; --i;) {
            x *= i;
        }
        return x;
    } catch (e) {
        console.log("e ", e);
    }
}

component.ts:

public computeFactorials() {
    this.factorialService.computeFactorials(this.firstFactorial, this.numberOfFactorials)
      .subscribe((res: any) => {

      }, (err) => {

      });
  }

上面的代码出了什么问题,我错过了任何import语句吗?有没有更好的方法将promises数组转换为observable?

2 个答案:

答案 0 :(得分:0)

您应该导入要在应用程序中使用的任何运算符:

请在server.ts文件中尝试以下内容:

import 'rxjs/add/operator/concatAll';

答案 1 :(得分:0)

我认为这就是你想要完成的事情,让我知道我是对的! live example

您可以使用Promise.all解析所有订单何时解决,然后转换为Observable,最后使用concatAll合并已解析的值。

import { fromPromise } from 'rxjs/observable/from';
import { concatAll } from 'rxjs/operators';

...

public computeFactorials(
  firstFactorial: number, 
  numberOfFactorials: number): Observable<number> {
    const promises: Promise<number> [] = [];
    for (let i = firstFactorial; i < firstFactorial + numberOfFactorials; i++) {
      const p: Promise<number> = this.asyncFunction(i);
      promises.push(p);
    }

    return fromPromise(Promise.all(promises)).pipe(concatAll());
}