2

我已经创建了一个组件:Angular2 + RxJS

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 undefinedthis.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> 

enter image description here

回答

4

此代码this.currentMonthObserver = observer;

this.currentMonth$ = new Observable((observer: Observer<Moment>) => { 
    this.currentMonthObserver = observer; 
}).share(); 
只有当您订阅 this.currentMonth时,才会执行

。 因此this.currentMonthObservernull,因为它没有被初始化。

constructor() { 
    this.currentMonth$=new Subject().startWith(0).share(); 
} 

increment() { 
    this.currentMonth$.next(1); 
} 

decrement() { 
    this.currentMonth$.next(-1); 
} 
+0

你能指出一个方法来在我得到异常之前初始化它吗?我在一个子组件中订阅它。 – vlio20

+0

我不确定你的代码是你真正想要完成的。为了使这一步工作,你需要调用'this.currentMonth.subscribe();'。 –

+0

我在模板上有2个按钮,应该将用户界面移动到下一个和上一个月。请参阅模板(在更新的问题中) – vlio20

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让你一个月