Angular:数组更改时如何更新视图?

时间:2018-12-03 17:38:28

标签: angular

我一直在阅读帖子并搜索该问题的答案,但没有成功

我没有看这两个链接

Angular doesn't update view when array was changed

Updating HTML view when Angular array changed

我有两个组成部分(兄弟姐妹) 一个组件添加项目,另一个列出所有添加的项目。这个想法非常简单,每当有人添加一个项目时,我想更新列表以获取该新项目。

export class ListItem implements OnInit {
  list: SomeObject[] = [];

  constructor(private myService: SomeService) {}

  ngOnInit() {
    this.getItems();
  }

  getItems(): void {
    this.myService.getDomesticatedPokemons()
      .subscribe((newItems) => {
        this.list = newItems; // I can see that this line works as expected but the view doesn't get updated though
      });
  }
}

export class AddItem implements OnInit {
  constructor(private myService: SomeService, private list: ListItem) {}

  ngOnInit() {

  }

  saveItem(aForm: NgForm): void {
    // ...
    // ...
    // ...
    // ...

    this.myService.addItem({}).subscribe((result) => {
      if (result.ok === 1) {
        this.list.getItems();
      } else {
        console.error('Error: ...');
      }
    });


  }
}

更新:

这是视图:

<!-- This is the list template -->
<div id="list">
    <div *ngFor="let item of list" class="item">
       ...
       ...
       ...
    </div>
</div>

对于添加组件,有一个表单,并且saveItem()在提交时执行

更新2: 我创建了一个stackblitz,尽管我无法(或至少我不知道如何)重现我的服务以从服务器获取数据,但该示例仍在工作。我注释掉了“更现实”的代码,其主要组成部分是列表。

1 个答案:

答案 0 :(得分:0)

我试图解决您的问题陈述:

要插入列表的组件

视图:

<h3>create list</h3>
Foo:
<input type="text" class="form-field" [(ngModel)]="newItem.foo"><br/>
Bar:
<input type="text" class="form-field" [(ngModel)]="newItem.bar"><br/>
<button class="btn" (click)="addItem()">Add</button>
<button class="btn" (click)="resetForm()">Reset</button>
<hr>

控制器:

export class CreateListComponent  {
  public newItem:Object;

  constructor(private listService: ListService) {
    this.newItem = this.setInital();
  }

  private setInital(){
    return {
      foo: null,
      bar: null
    };
  }
  public addItem(){
    this.listService.addItem(this.newItem);
    this.resetForm();
  }

  public resetForm(){
    this.newItem = this.setInital();
  }
}

显示列表的组件

视图:

<h3>display list</h3>

<div *ngFor="let item of list">
  {{item.foo}} - {{item.bar}}
</div>

控制器:

export class DisplayListComponent implements OnInit, OnDestroy {
  public list = [];
  private subscription: Subscription;

  constructor(private listService: ListService) { }

  ngOnInit() {
    this.getList();
  }

  private getList() {
    this.subscription = this.listService.getFooBarList().subscribe(data => {
        this.list.push(data);
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

由于两个组件都处于同一层次结构,因此我使用了服务并且可观察到的将数据从创建组件传递到显示组件

服务:

export class ListService {
  private listSubject = new Subject();

  constructor() {}

  public addItem(item: any) {
    this.listSubject.next(item);
  }

  public getFooBarList() {
    return this.listSubject.asObservable();
  }
}

希望这对您有所帮助。 For a working sample please refer this stackblitz