Observable.of is not a function

2019-01-08 06:48发布

I am having issue with importing Observable.of function in my project. My Intellij sees everything. In my code I have:

import {Observable} from 'rxjs/Observable';

and in my code I use it like that:

return Observable.of(res);

Any ideas?

标签: angular rxjs
19条回答
仙女界的扛把子
2楼-- · 2019-01-08 07:31

I am using Angular 5.2 and RxJS 5.5.6

This code did not work:

     import { Observable,of } from 'rxjs/Observable';

     getHeroes(): Observable<Hero[]> {
        return of(Hero[]) HEROES;

      }

Below code worked:

    import { Observable } from 'rxjs/Observable';
    import { Subscriber } from 'rxjs/Subscriber';

     getHeroes(): Observable<Hero[]> 
     {
          return Observable.create((observer: Subscriber<any>) => {
              observer.next(HEROES);
              observer.complete();
          });

      }

Calling method:

this.heroService.getHeroes()
      .subscribe(heroes => this.heroes = heroes);

I think they might moved/changed of() functionality in RxJS 5.5.2

查看更多
狗以群分
3楼-- · 2019-01-08 07:31

This should work properly just try it.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
查看更多
相关推荐>>
4楼-- · 2019-01-08 07:33

If you are using Angular 6 /7

import { of } from 'rxjs';

And then instead of calling

Observable.of(res);

just use

of(res);
查看更多
爷、活的狠高调
5楼-- · 2019-01-08 07:33

Somehow even Webstorm made it like this import {of} from 'rxjs/observable/of'; and everything started to work

查看更多
贼婆χ
6楼-- · 2019-01-08 07:36

You could also import all operators this way:

import {Observable} from 'rxjs/Rx';
查看更多
不美不萌又怎样
7楼-- · 2019-01-08 07:37
// "rxjs": "^5.5.10"
import { of } from 'rxjs/observable/of';

.... 
return of(res)
查看更多
登录 后发表回答