【发布时间】:2021-04-28 09:06:05
【问题描述】:
我刚刚学习 Angular,但在将方法传递给另一个组件时遇到了麻烦。 对象项有文档数组,我想删除给定 id 的文档
api / item / {itemId} / deleteDocument / {documentId}。此端点来自 springboot 后端并从数据库中的项目数组中删除文档。 这就是我所拥有的:
item.service.ts
@Injectable({
providedIn: 'root'
})
export class ItemService {
private serviceUrl = 'api/item/';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private http: HttpClient) {}
deleteDocument(itemId: number, documentId: number): Observable<any>{
return this.http.delete(this.serviceUrl + itemId +'/deleteDocument/' + documentId).pipe();
}
item-component.ts
这里我想从Item的文档列表中删除文档。
export class ItemComponent implements OnInit {
item: ItemElem = new ItemElem();
constructor(private itemService: ItemService, public route: ActivatedRoute) { }
ngOnInit(): void {
const id = this.route.snapshot.paramMap.get('id');
this.itemService.getById(id).subscribe(p => {
this.item = p;
});
this.itemService.getDocumentList(id).subscribe(docList => {
this.item.documents = docList;
});
}
onDeleteDocument(document: DocumentListItem) {
this.itemService.deleteDocument(this.item.id, document.id).subscribe(p => {
this.item.documents = this.item.documents.filter(
doc => doc.id !== document.id);
});
}
文档列表组件.ts
deleteItem(element) {
// HERE
}
private prepareDocumentActions() {
return [
{
name: 'edit',
makeAction: (elem: DocumentListItem) => {
window.open(elem.documentOpenUrl);
}
{
name: 'delete',
makeAction: (elem: DocumentListItem) => {
this.deleteItem(elem.id);
}
},
];
}
和html:
<div fxLayout="row" fxLayoutAlign="space-around none" >
<div *ngFor="let action of documentActions">
<button mat-icon-button color="primary" (click)="action.makeAction(element)">
<mat-icon class="md-24">{{action.name}}</mat-icon>
</button>
</div>
</div>
所以,我想提供从 item-component.ts 到 document 到 document-list-component.ts 的方法,在那里我有 deleteDocument() 方法。在视图中,我有一个按钮,单击后将从 Item 中的文档数组中删除文档,当然还有从 db 中删除文档。
这可能是一项微不足道的任务,但我每天都在 java 和 sprinboot 中工作,而且我不知道 Angular。如有任何帮助,我将不胜感激。
你好!!
【问题讨论】:
-
简而言之,您不应该这样做。我建议研究实现 redux 模式的 ngrx 或类似的包。如果您不想这样做,请使用具有行为主题的服务,该服务将包含文档列表和添加/删除/编辑的方法。保持 BS 私有,并公开 BS 的方法和可观察对象。并寻找智能/演示组件概念。
标签: angular typescript data-binding components