尝试使用以下类实现observable
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);
}
}
使用值调用setDate()
时出现以下错误
ORIGINAL EXCEPTION: TypeError: Cannot read property 'next' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'next' of undefined
似乎没有定义观察者dataChangeObserver
。但是在调试时我可以看到我设置的dataChangeObserver
值。但是Ionic 2在调用setDate(date: any)
时会以某种方式忘记它。