我在顯示列表的同一頁上有刪除操作。當我執行刪除時,api中的數據發生了變化,但它並未反映在列表本身中。在api上執行編輯或刪除操作後,角度2視圖不更新
我嘗試了幾件事情之一,即將已刪除的對象從可觀察數組中拉出來。這不起作用,這不是我想要的,因爲它不會反映其他用戶是否添加或刪除了列表中的「人員」。
現在唯一可行的是在刪除操作完成後觸發api調用,但效率不高。
在我看來,正確的方法將觸發或刷新訂閱,以便它返回到api獲取新數據並添加新數據或刪除數據庫中不存在的數據到可觀察數組。
有沒有辦法使用observable和RxJs來完成它?
謝謝大家幫忙
import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {PeopleService} from '../shared/people.service';
import {People} from '../shared/people.model';
import {ToastService} from '../../../core/toast/toast.service';
@Component({
selector: 'app-people-list',
templateUrl: './people-list.component.html',
styleUrls: ['./people-list.component.css']
})
export class PeopleListComponent implements OnInit {
peoples: Observable<People[]>;
constructor(private peopleService: PeopleService,
private toastService: ToastService) { }
getPeoples() {
this.peoples = this.peopleService.getPeoples()
}
deletePeople(people: People) {
this.peopleService.deletePeople(people)
.subscribe(
() => {
this.toastService.activate(' Deleted', 'People', 'danger');
},
(err) => console.log('Debug:deletefailed', err)
);
}
ngOnInit() {
this.getPeoples();
}
}
<div>
<h3>People List</h3>
<hr/>
<a href="" [routerLink]="['/peoples', 'new']"><button class="btn btn-primary">Add People</button></a>
<table class="table table-hover">
<thead class="thead-inverse">
<tr>
<th>Id</th>
<th>Number of People</th>
<th>Modify</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let people of peoples | async">
<th>{{people.id}}</th>
<td>{{people.purchaseCount}}</td>
<td><button href="#" [routerLink]="['/peopleDetail', people.id]" class="btn btn-sm btn-info">Edit/Detail</button></td>
<td><button (click) = "deletePeople(people)" class="btn btn-sm btn-danger">Delete</button></td>
</tr>
</tbody>
</table>
</div>
'peoples:Observable;'你爲什麼要在你的組件中觀察你的可觀察性? –
Aravind
該服務返回一個observable,如果我在getPeople方法中訂閱服務,它也可能只是一個數組而不是可觀察的。 – Virodh