import .of() for Observable in typescript

自闭症网瘾萝莉.ら 提交于 2019-12-19 05:08:38

问题


I'm using this great repo for my angular 2 test project (TypeScript) - https://github.com/qdouble/angular-webpack2-starter. And I need to use Observable.of(..). When I try to import it:

import { Observable } from "rxjs/Observable";
import { of } from 'rxjs/observable/of';

I get:

Property 'of' does not exist on type 'typeof Observable'.

I also tried it the following way:

import { Observable } from "rxjs/Observable";
import { of } from 'rxjs/add/observable/of'; // notice 'add'

I got:

node_modules/rxjs/add/observable/of"' has no exported member 'of'.

So, how can one import this Of() static method for Observable???


回答1:


You do not have to import {of} from 'rxjs/add/observable/of'. You can directly use

import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/of";

Or you can import Observable from "rxjs/Rx" which bundle all the operators. Bad practice

import { Observable } from "rxjs/Rx";

Update 2018-01-26: RxJS v5.5+ pipeable operators

From https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md

Starting in version 5.5 we have shipped "pipeable operators", which can be accessed in rxjs/operators (notice the pluralized "operators"). These are meant to be a better approach for pulling in just the operators you need than the "patch" operators found in rxjs/add/operator/*.

Now that "patching" imports are going to be deprecated, it would be better to use strict imports.

import { of as observableOf } from 'rxjs/observable/of'

and use it like that

const myObs$: Observable<number> = observableOf(1, 2, 3)



回答2:


RxJS 6

Starting with RxJS 6, the imports were greatly simplified and cause less confusion now thanks to a more intuitive API surface:

  1. Creation methods like of are directly imported from 'rxjs':

    import { of } from 'rxjs';

  2. All pipeable operators are imported from 'rxjs/operators', e.g.:

    import { tap, map } from 'rxjs/operators';


Migration:

If you're updating directly from RxJS 5, you can even utilize the TSLint rules for RxJS, which will automatically fix your imports to the newer, simplified API:

  1. npm i -g rxjs-tslint
  2. rxjs-5-to-6-migrate -p [path/to/tsconfig.json]


来源:https://stackoverflow.com/questions/40579452/import-of-for-observable-in-typescript

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