Typescript rxjs Observable array concat

天涯浪子 提交于 2019-12-11 01:28:27

问题


I am having trouble using rxjs Observable.concat function with typescript. Getting an error "Cannot read property 'apply' of undefined"

The problem seems to be only within typescript and may be specific to rxjs version 5 concat. The code seems to work with rxjs V4.

Here is a simplified version of the code illustrating the problem...

 /*jshint esnext: true */

console.clear();
console.log('started');
class test{
    observableArray: Observable<any>[]=[];

    constructor(){
        this.observableArray.push(Rx.Observable.return("Line 1"));
        this.observableArray.push(Rx.Observable.return(56));
        this.observableArray.push(Rx.Observable.create((observer)=>{
             setTimeout(()=>{
                try{
                    observer.onNext("Waited for");
                    observer.onCompleted();
                }
                catch(err){
                     observer.onError(err);
                }
             },3000);
         }));
      }

    run(){
         // ... indeterminate number of observables pushed into array.
         // The problem lies below
         var source = Rx.Observable.concat(...this.observableArray);
         // seems to transpile into js: source =   Observable_1.Observable.concat.apply(Observable_1.Observable, this.observableArray);
         // In the chrome debugger I am getting error: Cannot read property 'apply' of undefined      

         var subscription = source.subscribe(
             function (x) {
                 console.log('Next: ' + x);
             },
             function (err) {
                 console.error('Error: ' + err);
             },
             function () {
                 console.log('Completed');
         });
      }
  }

}

Here is the jsbin: https://jsbin.com/naxeba/edit?html,js,console,output


回答1:


OK, Problem solved.

Important note for users of reactive js version 5: In typescript with rxjs, to minimize app size each operator must be specifically imported for the function/operator to be included. So the line...

import {concat} from 'rxjs/operators/concat' must be inlcuded at the top of the typescript file for concat to work.

What confused me was that I was getting intellisense in VS2015 for the Observable.concat function even though the function had not actually been imported.




回答2:


I'm using rxjs 5.5.7 and had to use import 'rxjs/add/observable/concat';.

The code itself looks like: Observable.concat(...observables).subscribe etc



来源:https://stackoverflow.com/questions/36585491/typescript-rxjs-observable-array-concat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!