添加元素时复制存储在数组中的对象

时间:2019-05-20 17:34:22

标签: javascript angular typescript

作为初学者,我正在开发angular的应用程序。该应用程序会记录笔记并将其存储在DB中。

添加过程中我遇到了一个问题。如果DB中没有现有数据,并且我添加了两个新注释,则两个注释在UI中显示为相同。尽管新注释和旧注释已存在于数据库中。

enter image description here

我观察到一件事。从数据库返回的数据为JSON格式。 添加新数据时,注释数组显示为-

0: {}
1: {}
2: Note{}
3: Note{}

NoteService-

export class NotesService {

  private baseURL = 'http://localhost:8082/api/v1/note';
  notes: Note[];
  notesSubject: BehaviorSubject<Note[]>;

  constructor(private http: HttpClient) {
    this.notes = [];
    this.notesSubject = new BehaviorSubject<Note[]>([]);
  }

  private extractData(res: Response) {
    let body = res;
    return body;
  }

  fetchNotesFromServer(): Observable<Note[]> {
    return this.http.get(`${this.baseURL}/${sessionStorage.getItem("userId")}`)
      .map(this.extractData)
      .catch(this.handleErrorObservable);
    ;
  }

  getNotes(): BehaviorSubject<Note[]> {
    this.fetchNotesFromServer().subscribe(
      notes => { this.notes = notes; this.notesSubject.next(this.notes) },
      error => this.handleErrorObservable(error));
    return this.notesSubject;
  }

  addNote(note: Note): Observable<Object> {
    return this.http.post(this.baseURL, note, { observe: 'response' });
  }

  private handleErrorObservable(error: HttpErrorResponse | any) {
    console.error(error.message || error);

    return Observable.throw(new HttpErrorResponse(error));
  }
}

NoteTakerComponent:addNote()-

addNote(): void {
        this.errMessage = '';
        if (this.validateNote()) {
          this.note.noteCreatedBy = sessionStorage.getItem("userId");
          this.note.noteTitle = this.noteTitle;
          this.note.noteContent = this.noteContent;
          this.note.noteStatus = this.state;
          this.note.category = this.editCategory;
          this.note.reminder = this.editReminder;
          let maxId = 0;
          if (this.noteService.notes.length > 0) {
            this.noteService.notes.forEach(note => {
              if (note.noteId > maxId) {
                maxId = note.noteId;
              }
            });
          }
          this.note.noteId = ++maxId;
          this.noteService.addNote(this.note).subscribe(response => {
            this.noteService.notes.push(this.note);
            this.noteService.notesSubject.next(this.noteService.notes);
            console.log('note taker', this.noteService.notes);
            this.reset();
          },
            error => this.handleErrorResponse(error));
        }
      }

NoteTaker视图-

<!-- Expansion panel to add new notes -->
<div class="keep-note-expansion-panel">
  <mat-accordion>
    <mat-expansion-panel>
      <mat-expansion-panel-header>
        <mat-panel-title>Take a note</mat-panel-title>
      </mat-expansion-panel-header>

      <div class="keep-note-form-container">
        <mat-form-field>
          <input matInput class="note-full-width form-control" name="title" placeholder="title" [(ngModel)]="noteTitle"
            required>
        </mat-form-field>

        <mat-form-field>
          <textarea matInput class="note-full-width form-control" name="text" placeholder="text"
            [(ngModel)]="noteContent" required></textarea>
        </mat-form-field>

        <mat-form-field>
          <mat-select name="Status" placeholder="Select state" [(ngModel)]="state">
            <mat-option *ngFor="let state of states" [value]="state">
              {{ state }}
            </mat-option>
          </mat-select>
        </mat-form-field>

        <mat-form-field>
          <mat-select name="category" placeholder="Select Category" [(ngModel)]="editCategory">
            <mat-option *ngFor="let category of categories" [value]="category">
              {{ category.categoryName }}
            </mat-option>
          </mat-select>
        </mat-form-field>

        <mat-form-field>
          <mat-select name="reminder" placeholder="Select Reminder" [(ngModel)]="editReminder" multiple>
            <mat-option *ngFor="let reminder of reminders" [value]="reminder">
              {{ reminder.reminderName }}
            </mat-option>
          </mat-select>
        </mat-form-field>

        <button mat-button (click)="addNote()">Done</button>
      </div>
    </mat-expansion-panel>
  </mat-accordion>
</div>

NoteView组件-

 export class NoteViewComponent implements OnInit {
  notes: Note[];
  errorMessage: String;
  constructor(private noteService: NotesService) {

  }
  ngOnInit(): void {
    this.noteService.getNotes().subscribe(
      notes => {
        this.notes = notes;
        console.log('note view', this.notes);
      },
      error => this.handleErrorResponse(error));
  }

}

预期结果是显示新添加的注释和旧注释。

1 个答案:

答案 0 :(得分:0)

存在一个基本错误,即修改了同一笔记对象而不是创建新对象。

修改后的NoteTaker组件-

addNote(): void {
    this.errMessage = '';
    this.note = new Note();
    if (this.validateNote()) {
      this.note.noteCreatedBy = sessionStorage.getItem("userId");
      this.note.noteTitle = this.noteTitle;
      this.note.noteContent = this.noteContent;
      this.note.noteStatus = this.state;
      this.note.category = this.editCategory;
      this.note.reminder = this.editReminder;
      let maxId = 0;
      if (this.noteService.notes.length > 0) {
        this.noteService.notes.forEach(note => {
          if (note.noteId > maxId) {
            maxId = note.noteId;
          }
        });
      }
      this.note.noteId = ++maxId;
      this.noteService.addNote(this.note).subscribe(response => {
        this.noteService.notes.push(this.note);
        this.noteService.notesSubject.next(this.noteService.notes);
        console.log('note taker', this.noteService.notes);
        this.reset();
      },
        error => this.handleErrorResponse(error));
    }
  }