Angular View не обновляется при нажатии массива - PullRequest
0 голосов
/ 12 октября 2018

Я очень плохо знаком с ионным и угловатым.В любом случае, я пытаюсь следовать руководству по созданию приложения для заметок, используя 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>

1 Ответ

0 голосов
/ 12 октября 2018

Я следовал тому же учебнику и получил ту же проблему.Проблема в том, что что-то очень интересное и мощное называется Зоны .

Идея состоит в том, что вам нужно сообщить 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();
      });
  }

}
...