【问题标题】:Best way to create Observable, using from, in RxJS 5.x?在 RxJS 5.x 中使用 from 创建 Observable 的最佳方法?
【发布时间】:2017-11-15 00:36:48
【问题描述】:

现在我们有了“可出租”运算符,我们应该如何从另一个创建Observable

当我尝试这样做时:

import {Observable} from 'rxjs/Observable'
const source = Observable.from(someOtherStream)

我收到错误 Observable.from is not a function,这是有道理的,因为 from 现在是需要单独导入的其他内容。

我不想做

import 'rxjs/add/observable/from' 不再是由于那里的原型问题。

我最终做的是:

import { Observable } from 'rxjs/Observable'
import { from } from 'rxjs/observable/from'

const myNewStream = from.call(
  Observable,
  someOtherStream
)

但出于某种原因,这对我来说真的感觉很“骇人听闻”。有没有人有更好的方法来解决这个问题?

【问题讨论】:

标签: javascript rxjs rxjs5


【解决方案1】:

我认为这是对from 所做的事情的误解。它只是一个接受“流”(即 Observable、Promise、数组...)并从中创建 Observable 的函数。

这意味着您可以像使用任何其他功能一样使用它:

import { from } from 'rxjs/observable/from'

from(someOtherStream).pipe(...).subscribe(...)

【讨论】:

    【解决方案2】:

    lettables 在 rxjs/operators here's the write up on it 后面。

    对于from,您应该能够在不导入 Observable 的情况下导入它。

    import { from } from 'rxjs/observable/from';
    
    const prom = new Promise(res => setTimeout(
      () => res('promise'), 3000
    ));
    
    from(prom).subscribe(x => console.log(x));
    

    webpackbin example

    以这种方式使用from 允许您将pipe() 用于可出租的运算符。

    import { from } from 'rxjs/observable/from';
    import { map } from 'rxjs/operators/map';
    
    const prom = new Promise(res => setTimeout(
      () => res('promise'), 3000
    ));
    
    from(prom).pipe(
      map(x => x.split('').reverse().join(''))
    ).subscribe(x => console.log(x));
    

    webpackbin example

    【讨论】:

    猜你喜欢
    • 2021-01-01
    • 2017-07-11
    • 2017-07-17
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多