当我修改 Material Angular 的 subscribe 块内的 books 变量时,视图没有更新dialogRef.afterClosed().subscribe()

问题描述 投票:0回答:1

books.component.ts
文件中

export class BooksComponent{
  // books variable
  books: IBook[] = [];

  // constructor to initialize BookService
  constructor(private bookService: BookService) {}

  // Handle Dialog
  readonly dialog = inject(MatDialog);

  openDialog() {
    const dialogRef = this.dialog.open(BookAddDialogComponent, {
      data: { booksCount: this.books.length },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        const newBook = dialogRef.componentInstance.newBook;
        console.log(newBook); // { id: 0. title: 'Harry Potter', author: 'J.K. Rowling'}
        this.books = this.bookService.addBook(this.books, newBook);
        console.log(this.books); // [{ id: 0. title: 'Harry Potter', author: 'J.K. Rowling'}]
      }
    });
  }

}

books.component.html
文件中

  <h4>Book List ({{ books.length }})</h4>
  <ul>
    <li *ngFor="let book of books">
      {{ book.id }} - {{ book.title }} - {{ book.author }}    
    </li>
  </ul>

我已经检查过控制台。它显示了

newBook
this.books
的正确值。但它没有显示在 html 文件中。

我尝试在

this.books
中设置
localStorage
变量,然后将其取回,以便
this.books
能够重新加载。然后它就起作用了,当我刷新页面时,它已成功添加新书并显示在视图中。但如果不重新加载,它就不会在视图中更新。

我还尝试修改

a
块内的虚拟变量
subscribe

export class BooksComponent{
  a: number = 0;

  // Handle Dialog
  readonly dialog = inject(MatDialog);

  openDialog() {
    const dialogRef = this.dialog.open(BookAddDialogComponent);

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
       this.a = 1;
       console.log(a) // 1
      }
    });
  }

}

books.component.html
文件中

  <h4> {{ a }} </h4> // 0

视图中仍然没有更新。

a
视图中仍然显示 0。
console.log(a)
显示 1,但在视图中它没有变化。

此问题仅发生在订阅块内。如果我像这样对块外的变量进行任何更改

export class BooksComponent{
  a: number = 0;

  // Handle Dialog
  readonly dialog = inject(MatDialog);

  openDialog() {
    const dialogRef = this.dialog.open(BookAddDialogComponent);

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
       
      }
    });

    this.a = 1;
    console.log(a) // 1
  }

}

books.component.html
文件中

  <h4> {{ a }} </h4> // 1

然后它就可以正常工作并在视图中显示出适当的价值。

请帮我解决这个问题。

angular angular-material
1个回答
0
投票

添加 ChangeDetectorRef.markForCheck() 修复了问题

// in constructor
  constructor(
    private bookService: BookService,
    private cd: ChangeDetectorRef // added
  ) {}

// In open dialog function
  openDialog() {
  ... 
   dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        const newBook = dialogRef.componentInstance.newBook;
        this.books = this.bookService.addBook(this.books, newBook);
        this.openSnackBar('New Book Added', 'Close');
        this.cd.markForCheck(); // added
      }
   });
© www.soinside.com 2019 - 2024. All rights reserved.