Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 import shared operator for Observable

I am trying to use the shared operator for Observers but it doesnt works:

My ts code:

import { Injectable } from '@angular/core';
import { Observer } from 'rxjs/observer';
import { Observable } from 'rxjs/observable';
import 'rxjs/add/operator/share';

@Injectable()
export class LoadingService {
    private _observer: Observer<string>;
    loading$: Observable<string>;
    constructor() {
        this.loading$ = new Observable<string>(
            observer => this._observer = observer).share();
    }

    toggleLoadingIndicator(name) {
        if (this._observer) {
            this._observer.next(name);
        }
    }
}

When I invoke the .share(); I get the error: TypeError: (intermediate value).share is not a function.

In other case I importing successfully for example the map operator, and using normally like this:

import 'rxjs/add/operator/map';
this._http.get(this._url, {
    headers: this._headers
}).map(r => r.json()).subscribe(json => {
    console.log(json);
    this.isValid = true;
});

So, even if I try to use the map operator, to proof the import, in the first scenario this.loading$ = new Observable<string>(observer => this._observer = observer).map(n => n); I get the same error.

like image 333
iuristona Avatar asked Nov 23 '25 10:11

iuristona


2 Answers

iuristona's answer works, but only because you're importing the entire library with:

import { Observable } from 'rxjs/Rx';

By importing from only the 'rxjs/Observable' module, you're only importing a few of the methods. Mobile users will appreciate only importing the methods you need rather than the entire library. You can do this with:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';  // added method
import 'rxjs/add/operator/map';           // added method

Hope that helps.

like image 104
user3386826 Avatar answered Nov 26 '25 03:11

user3386826


So, I dont know why, but when I import from 'rxjs/Rx', it works:

import { Observable, Observer } from 'rxjs/Rx';
like image 38
iuristona Avatar answered Nov 26 '25 03:11

iuristona