重构以使Angular组件更好

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

我在Typescript中编写了以下Angular组件:

export class ItemsComponent implements OnInit {

@Input()
invoice: Document;

@Input()
declaration: Document;

private invoiceName: string;
private declarationName: string;

constructor(private dataService: DataService) {
}

ngOnInit(): void {
    this.getInvoiceName(this.invoice);
    this.getDeclarationName(this.declaration);
}

getDeclarationName(declaration: Document) {
    this.dataService.getDocumentName(declaration.id)
        .subscribe((name) => this.declarationName = name);
}

getInvoiceName(invoice: Document) {
    this.dataService.getDocumentName(invoice.id)
        .subscribe((name) => this.invoiceName = name);
}

我有两个相同类型的项目,但我将它们作为来自不同组件的输入,然后我分别在我的html模板中使用它们。我现在所拥有的是好的和有效的,但我发现它太重复了,它闻起来对我来说。

你知道我怎么能重构它,所以我得到一个像getDocumentName这样的方法,我可以在onInit中调用它一次但是分别得到我的invoice和我的declaration的名字?

angular typescript refactoring
1个回答
1
投票

你可以做这样的事情

ngOnInit(): void {
    this.getDocumentNames();
}

getDocumentNames() {
    this.dataService.getDocumentName(this.declaration.id)
        .subscribe((name) => this.declarationName = name);
    this.dataService.getDocumentName(this.invoice.id)
        .subscribe((name) => this.invoiceName = name);
}

然后在dataservice级别上,您可以执行共享以优化http调用。

或者既然您想要同时检索多个名称,可以考虑更改dataService以支持接收Ids数组的方法,并且只对组件进行一次调用

© www.soinside.com 2019 - 2024. All rights reserved.