【问题标题】:Angular not detecting change to first element in array角度未检测到数组中第一个元素的更改
【发布时间】:2018-04-18 00:47:35
【问题描述】:

我正在尝试在 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);
    }
}

【问题讨论】:

    标签: arrays angular typescript asynchronous


    【解决方案1】:

    试试这个,我评论了中间的那一行,它正在工作,你能检查一下吗:

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

    【讨论】:

    • 您认为这与 Angular 更改检测有关吗?因为有了那一行,应用程序实际上更新了 dates[0] 两次,也许 Angular 只识别第一个更改?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    相关资源
    最近更新 更多