Angular未检测到数组中第一个元素的更改

时间:2017-11-05 21:57:04

标签: arrays angular typescript asynchronous

我试图在Angular应用中显示当前周的日期列表。我希望用户只需点击一下按钮即可查看前几周,因此我使用Observable更新日期数组,并尝试显示更新后的数组。

除了数组中的第一项外,视图中的所有项都会更新。 Plunker example here

我尝试过使用* ngFor和异步管道,以及为数组中的每个项目显式创建元素(如下所示)。两者都有同样的问题。我很难找到解决方案。

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'my-app',
  template: `
    <button (click)="previousWeek()">Prev Week</button>
    <div>{{dates[0]}}</div>
    <div>{{dates[1]}}</div>
    <div>{{dates[2]}}</div>
  `,
})
export class App {
  name:string;
  dates: Date[];
  public $datesSource: Observable<Date[]>;
  private datesSource: Subject<Date[]>;

  constructor() {
    this.datesSource = new Subject<Date[]>();
    this.datesSource$ = this.getDatesWithObservable();
    this.datesSource$.subscribe((dates) => {
      console.log(dates);

      this.dates = dates;
    })

    this.setDates(new Date());
  }

  setMonday(date: Date): Date {
        const day = date.getDay() || 7;
        if (day !== 1) {
            date.setHours(-24 * (day - 1));
        }
        return date;
    }

  setDates(date: Date): void {
        const dates = [
            new Date(),
            new Date(),
            new Date(),
            new Date(),
            new Date(),
            new Date(),
            new Date()
        ];
        const monday = this.setMonday(date);
        dates[0] = monday;
        const mondayDate = monday.getTime();
        dates.forEach((date, idx) => {
            console.log(idx);

            date.setTime(monday.getTime() + (idx * 24 * 60 * 60 * 1000));
    });
        this.addDates(dates);
    }

    addDates(dates: Date[]): void {
        this.datesSource.next(dates);
    }

    getDatesWithObservable(): Observable<Date[]> {
        return this.datesSource.asObservable();
    }


    previousWeek(): void {
      const day = this.dates[0].getDay() || 7;
      const lastWeek = this.dates[0];
      const days = 7;
      lastWeek.setTime(lastWeek.getTime() - (days * 24 * 60 * 60 * 1000));
      this.setDates(lastWeek);
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个,我评论中间的线路并且它正在工作,你能查一下:

     const monday = this.setMonday(date);
     //dates[0] = monday;
     const mondayDate = monday.getTime();