ionic-framework icon indicating copy to clipboard operation
ionic-framework copied to clipboard

Implementing observable fails because ionic 2 forgets Observer

Open wicketyCode opened this issue 10 years ago • 4 comments

Am trying to implement observable with the following class

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

@Injectable()
export class CalendarService {

    dataChange: Observable<any>;
    dataChangeObserver: Observer<any>;

    constructor() {
        this.dataChange = new Observable((observer) => {
            this.dataChangeObserver = observer;
        }).share();
    }

    setDate(date: any) {
        this.dataChangeObserver.next(date);
    }
}

When calling setDate() with a value am getting the following error

ORIGINAL EXCEPTION: TypeError: Cannot read property 'next' of undefined ORIGINAL STACKTRACE: TypeError: Cannot read property 'next' of undefined

It seems that the Observer dataChangeObserver is not defined. But when debugging i can see that dataChangeObserver value i set. But Ionic 2 somehow forgets about it when calling setDate(date: any).

wicketyCode avatar Sep 26 '16 12:09 wicketyCode

Hello, thanks for using Ionic! Does this error also happen in a plain Angular 2 project?

jgw96 avatar Sep 26 '16 19:09 jgw96

Hi Justin, I haven't tested it in a plain "angular 2" project but the code is inspired from a "angular 2" tutorial so it should work with "angular 2"

wicketyCode avatar Sep 27 '16 07:09 wicketyCode

Hello, sorry for any confusion! The reason I am asking you to try in a plain angular 2 project is because I am trying to narrow this issue down. Ionic 2 does nothing special with observables which means that Ionic 2 and Angular 2 should have the exact same behavior.

jgw96 avatar Sep 28 '16 18:09 jgw96

@jgw96 is correct. More than likely there is a bug in your code. This sounds like an issue that is outside the scope of Ionic.

Consider checking out the Ionic Forum. It's a great place to go for help with stuff like this.

Thanks, Dan

danbucholtz avatar Sep 28 '16 20:09 danbucholtz