Angular 数组推送时视图不刷新

Angular View does't refresh on array push

我对 ionic 和 angular 很陌生。 无论如何,我正在尝试按照教程使用 ionic4 https://www.joshmorony.com/building-a-notepad-application-from-scratch-with-ionic/.

创建笔记应用程序

所以,我按照说明操作。一切正常,除了当我添加新笔记时视图没有更新。代码如下:

备注服务:

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

import { Note } from '../interfaces/note';

@Injectable({
  providedIn: 'root'
})
export class NotesService {

  public notes: Note[] = [];
  public loaded: boolean = false;

  constructor(private storage: Storage) {

   }

  load(): Promise<boolean> {

    // Return a promise so that we know when this operation has completed
    return new Promise((resolve) => {

      // Get the notes that were saved into storage
      this.storage.get('notes').then((notes) => {

        // Only set this.notes to the returned value if there were values stored
        if (notes != null) {
          this.notes = notes;
        }

        // This allows us to check if the data has been loaded in or not
        this.loaded = true;
        resolve(true);

      });

    });

  }

   save(): void {
     // Save the current array of notes to storage
     this.storage.set('notes', this.notes);
   }

   getNote(id): Note {
     // Return the note that has an id matching the id passed in
     return this.notes.find(note => note.id === id);
   }

   createNote(title): Promise<boolean> {
     return new Promise((resolve) => {
       // Create a unique id that is one larger than the current largest id
      let id = Math.max(...this.notes.map(note => parseInt(note.id)), 0) + 1;

       this.notes.push({
         id: id.toString(),
         title: title,
         content: ''
       });

      this.save();
      console.log('Service Log ' + this.notes);
      resolve(true);
    });
   }

 }

HTML代码:

<ion-header>
    <ion-toolbar color="primary">
        <ion-title>Notes</ion-title>
        <ion-buttons slot="end">
            <ion-button (click)="addNote()">
                <ion-icon slot="icon-only" name="clipboard"></ion-icon>
            </ion-button>
        </ion-buttons>
    </ion-toolbar>
</ion-header>
<ion-content>
    <ion-list>
        <ion-item button detail *ngFor="let note of notesService.notes" [href]="'/notes/' + note.id" routerDirection="forward">
            <ion-label>{{ note.title }}</ion-label>
        </ion-item>
    </ion-list>
</ion-content>

我遵循了相同的教程并遇到了相同的问题。这个问题是因为一些非常有趣和强大的东西叫做 .

想法是您需要让 Angular 知道带有注释的数组已更改,方法如下:

// Angular
import { Component, NgZone } from '@angular/core';

// Ionic
import { NavController, AlertController } from '@ionic/angular';

// Services
import { NotesService } from '../services/notes.service';
import { AlertOptions } from '@ionic/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(
    private ngZone: NgZone, // Add this in the constructor
    private navCtrl: NavController,
    private alertCtrl: AlertController,
    private notesService: NotesService,
  ) { }

  ngOnInit() {
    this.notesService.load();
  }

  addNote() {
    const alertOptions: AlertOptions = {
      header: 'New Note',
      message: 'What should the title of this note be?',
      inputs: [
        {
          type: 'text',
          name: 'title'
        }
      ],
      buttons: [
        {
          text: 'Cancel'
        },
        {
          text: 'Save',
          handler: (data) => {
            // Create the note inside a Zone so that Angular knows
            // that something has changed and the view should be updated
            this.ngZone.run(() => {
              this.notesService.createNote(data.title);
            });
          }
        }
      ]
    };

    this.alertCtrl
      .create(alertOptions)
      .then((alert) => {
        alert.present();
      });
  }

}