我一直在阅读帖子并在谷歌上搜索这个问题的答案,但没有成功
我查看了这两个链接,但什么也没有
Angular doesn't update view when array was changed
Updating HTML view when Angular array changed
我有两个组件( sibling ) 一个组件添加项目,另一个组件列出所有添加的项目。这个想法非常简单,每当有人添加一个项目时,我想更新列表以获得该新项目。
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: ...');
}
});
}
}
更新:
这是 View :
<!-- This is the list template -->
<div id="list">
<div *ngFor="let item of list" class="item">
...
...
...
</div>
</div>
对于添加组件,有一个表单,并在提交时执行 saveItem()
更新2: 我创建了一个stackblitz即使我无法(或者至少我不知道如何)重现从服务器获取数据的服务,这个示例仍然有效。我注释掉了“更现实”的代码,主要组件是列表。
最佳答案
我已尝试解决您的问题陈述:
要插入列表的组件
查看:
<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>
Controller :
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>
Controller :
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 .
关于Angular:数组更改时如何更新 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53598976/