Angular2 + RxJS - 无法读取未定义的属性

时间:2016-03-05 18:24:14

标签: angular functional-programming rxjs reactive-programming

我创建了下一个组件:

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

2 个答案:

答案 0 :(得分: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);
}

答案 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来获取月份