Angular 如何避免组件中的代码重复?

Angular 如何避免组件中的代码重复?,angular,Angular,我有以下组成部分: export class OrdersExecutionListComponent implements OnInit { public legend: Legend; constructor( public paginationService: PaginationService, public applicationService: ApplicationService, private listServi

我有以下组成部分:

export class OrdersExecutionListComponent implements OnInit {
    public legend: Legend;

    constructor(
        public paginationService: PaginationService,
        public applicationService: ApplicationService,
        private listService: ListService,
    ) {
        this.legend = legendRepository.legendExecution;
    }

    ngOnInit() {
        this.listService.onChanged.subscribe((sortedList: ListItem[]) => {
            const sortBy = sortedList.map((item) => item.key).join();
            this.getExecutionApplications(this.paginationService.getOffset(), this.paginationService.getLimit(), sortBy);
        });

        this.getExecutionApplications(this.paginationService.getOffset(), this.paginationService.getLimit());
    }

    getExecutionApplications(offset: number, limit: number, sortBy?: string): void {
        this.applicationService.getExecutionApplications(offset, limit, sortBy);
    }
}
正如您可以看到的那样,this.getExecutionApplications方法在ngInit中被调用两次,一次是默认调用,另一次是在订阅中出现技术时调用


我不喜欢这个符号。如何改进它?

假设您在订阅之外调用
getExecutionApplications
,因为
一旦更改
不会在初始化时触发,您可以使用
startWith
强制它发射,并且仅在相关的情况下通过
排序

ngOnInit() {
    this.listService.onChanged.pipe(startWith(null)).subscribe((sortedList: ListItem[]) => {
        const sortBy = sortedList ? sortedList.map((item) => item.key).join() : undefined;
        this.getExecutionApplications(this.paginationService.getOffset(), this.paginationService.getLimit(), sortBy);
    });
}

假设您在订阅之外调用
getExecutionApplications
,因为
onChanged
不会在初始化时触发,您可以使用
startWith
强制它发出,并且仅通过
排序(如果相关):

ngOnInit() {
    this.listService.onChanged.pipe(startWith(null)).subscribe((sortedList: ListItem[]) => {
        const sortBy = sortedList ? sortedList.map((item) => item.key).join() : undefined;
        this.getExecutionApplications(this.paginationService.getOffset(), this.paginationService.getLimit(), sortBy);
    });
}

它需要按默认值加载页面上的数据如果不调用默认值会发生什么?然后我不会在页面上获取信息,当我调用它时,我请求一个服务,使请求到达服务器。因此,我有一个服务方法,我可以在两种情况下调用它<代码>this.applicationService.getExecutionApplications(偏移量、限制、排序)
where
sortBy
是可选的。默认情况下需要在页面上加载数据。如果不调用默认值,会发生什么?然后我不会在页面上获取信息,当我调用它时,我请求一个服务,使请求到达服务器。因此,我有一个服务方法,我可以在两种情况下调用它<代码>this.applicationService.getExecutionApplications(偏移量、限制、排序)其中
sortBy
是可选的