我创建了下一个组件:
export class MonthView {
currentMonth: Moment = moment();
currentMonth$: Observable<Moment>;
currentMonthObserver: Observer<Moment>;
decrement: Function;
increment: Function;
constructor() {
this.currentMonth$ = new Observable((observer: Observer<Moment>) => {
this.currentMonthObserver = observer;
}).share();
const decrementCounter$: Observable<Function> = Observable.create((observer) => {
this.decrement = () => {
observer.next();
};
});
const incrementCounter$: Observable<Function> = Observable.create((observer) => {
this.increment = () => {
observer.next();
};
});
Observable
.merge(
decrementCounter$.map(() => - 1),
incrementCounter$.map(() => + 1)
)
.startWith(0)
.scan((currentCount: number, value: number) => currentCount + value)
.subscribe((count: number) => {
this.currentMonthObserver.next(this.currentMonth.clone().add(count, 'M')); //this.currentMonthObserver is undefined
});
}
}
问题:
我收到Cannot read property 'next' of undefined
行this.currentMonthObserver.next
(请参阅已发布代码中的评论)。
注意:我已经按照本博客上的教程进行操作,而且我是RxJS的新手:https://coryrylan.com/blog/angular-2-observable-data-services
模板:
<month-board [current-month]="currentMonth$"></month-board>
<button (click)="decrement()">Prev</button>
<button (click)="increment()">Next</button>
答案 0 :(得分:4)
中的此代码
this.currentMonthObserver = observer;
this.currentMonth$ = new Observable((observer: Observer<Moment>) => {
this.currentMonthObserver = observer;
}).share();
只有在您订阅this.currentMonth
时才会执行。
因此,this.currentMonthObserver
为null
,因为它未初始化。
constructor() {
this.currentMonth$=new Subject().startWith(0).share();
}
increment() {
this.currentMonth$.next(1);
}
decrement() {
this.currentMonth$.next(-1);
}
答案 1 :(得分:1)
不确定完全您正在尝试做什么,但假设您在视图中有按钮来指定和减去您的月份,我认为您可以简化一下:
export class MonthView {
currentMonth$: Observable<Moment>;
tickMonth$: new Subject<Number>();
constructor() {
this.currentMonth$ = tickMonth$
.scan((myMoment: Moment, tickMonthValue: number) => myMoment.clone().add(tickMonthValue, 'M'))
.startWith(new Moment());
}
}
然后在您的视图中,您可以分别执行(click)="tickMonth$.next(1)"
和(click)="tickMonth$.next(-1)"
来增加和减少月份
然后您只需使用currentMonth | async
来获取月份